問題描述:
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULLFollow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
翻轉鏈表問題,簡單的非遞歸做法:
/**
* 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* pre = head;
ListNode* p = head->next;
ListNode* t;
pre->next = NULL;
while(p != NULL)
{
t = p->next;
p->next = pre;
pre = p;
p = t;
}
return pre;
}
};