206. Reverse Linked List
Reverse a singly linked list.
用循环的方式:
/**
* 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 *tnow=head, *tnext=head->next, *tone;
head->next=NULL;
while(tnext != NULL){
tone = tnext->next;
tnext->next = tnow;
tnow = tnext;
tnext = tone;
}
return tnow;
}
};
用递归的方式:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (!head || !(head -> next)) return head;
ListNode* node = reverseList(head -> next);
head -> next -> next = head;
head -> next = NULL;
return node;
}
};