Saturday, April 2, 2016

LeetCode Q206: 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:
void helper(ListNode* head, int l){
if(l==0)
return;
ListNode* p=head;
int c=l;
while(c-- > 1){p=p->next;}
p->next->next=p;
p->next=NULL;
helper(head, l-1);
}
ListNode* reverseList(ListNode* head) {
if(head==NULL)
return head;
int l=0;
ListNode* newHead=head;
while(newHead->next!=NULL){
newHead=newHead->next;
l++;
}
helper(head, l);
return newHead;
}
};


/**
* 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* pre=head;
ListNode* cur = head->next;
pre->next = NULL;
ListNode* next;
while(cur!=NULL){
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
};
view raw Q206Rnd2.cpp hosted with ❤ by GitHub

No comments:

Post a Comment