基本思路
- 从元首节点之后每次取一个节点,并将节点接到元首节点前面
代码实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == NULL || head->next == NULL){
return head;
}
ListNode * a = head;
ListNode * c = head;
ListNode * b = head->next;
ListNode * t = NULL;
while(b != NULL){
//cout << b->val << endl;
t = b->next;
b->next = a;
a = b;
b = t;
//cout << a->val << endl;
}
//一定要记得处理第一个指针,使其指向NULL,否则将出现无法终止的情况
c->next = NULL;
//cout << 1 << endl;
return a;
}
};