一、题目描述
Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
思路:记录三个节点,前一个节点,当前节点,后一个节点。只需要修改next即可。画图很容易明白。
c++代码
迭代法(10ms)
/**
* 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) {
ListNode * current=head;
ListNode * next;
ListNode * last=NULL;
while(current != NULL){
next = current->next;
current->next = last;
last = current;
current = next;
}
return last;
}
};
递归(8ms)
/**
* 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 NULL;
else if(head ->next == NULL)
return head;
else{
ListNode * result = reverseList(head->next);
head->next->next = head;
head->next=NULL;
return result;
}
}
};