
非常经典,我写的比较复杂,一直以来的思路都是这样,就没有去找更简单的解法:(做链表题习惯加头结点的前置节点了,去掉也行)
cpp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* h=new ListNode(0,head);
ListNode* a=head;
if(head==nullptr||head->next==nullptr) return head;
ListNode* b=head->next;
ListNode* c=b->next;
a->next=nullptr;
while(c){
b->next=a;
a=b;
b=c;
c=c->next;
}
b->next=a;
h->next=b;
return h->next;
}
};
答案的缩略版,学到了(将原本的c放进函数内部):
cpp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre=nullptr;
ListNode* now=head;
while(now){
ListNode* nex=now->next;
now->next=pre;
pre=now;
now=nex;
}
return pre;
}
};