Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
题意:对链表进行逆序。
思路1:迭代逆序。
/**
* 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;
ListNode *p, *q, *r;
p = NULL;
q = head;
r = head->next;
while (r){
q->next = p;
p = q;
q = r;
r = r->next;
}
q->next=p;
return q;
}
};
思路2:递归逆序。
class Solution {
public:
ListNode* reverseList(ListNode* head) {
return recursion(NULL, head);
}
ListNode* recursion(ListNode* p, ListNode* q){
if (q == NULL)
return p;
else{
ListNode* r = q->next;
q->next = p;
return recursion(q, r);
}
}
};