AcWing 35. 反转链表
原题链接
简单
作者:
daniellee
,
2019-04-10 21:13:46
,
所有人可见
,
阅读 1061
C++ 代码
/**
* 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) return head;
if (head->next==NULL) return head;
ListNode* pre = head;
ListNode* c = head->next;
if (head->next->next==NULL){
c->next = head;
head->next =NULL;
return c;
}
ListNode* post = head->next->next;
while(c!=NULL){
c -> next = pre;
pre = c;
c = post;
if (c->next == NULL){
c->next = pre;
head->next = NULL;
return c;
}
post = c->next;
}
return c;
}
};