LeetCode 206. 反轉連結串列
阿新 • • 發佈:2018-12-12
反轉一個單鏈表。
示例:
輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL
進階: 你可以迭代或遞迴地反轉連結串列。你能否用兩種方法解決這道題?
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 || head->next==NULL) { return head; } ListNode* pcur=head,*pnext=NULL,*pnew=NULL; while(pcur) { pnext=pcur->next; pcur->next=pnew; pnew=pcur; pcur=pnext; } return pnew; } };