非常經典,我寫的比較復雜,一直以來的思路都是這樣,就沒有去找更簡單的解法:(做鏈表題習慣加頭結點的前置節點了,去掉也行)
/*** 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放進函數內部):
/*** 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;}
};