Tuesday, February 5, 2013

Remove Nth Node From End

/*Given a linked list, remove the nth node from the end of list and return its head.
 
 




For example,

Given linked list: 1->2->3->4->5, and n = 2.
 
 




After removing the second node from the end, the linked list becomes 1->2->3->5.

*/

/**

* Definition for singly-linked list.

* struct ListNode {

* int val;

* ListNode *next;

* ListNode(int x) : val(x), next(NULL) {}

* };

*/
 
 
 
 


ListNode *removeNthFromEnd(ListNode *head, int n) {

// Start typing your C/C++ solution below

// DO NOT write int main() function

if(n<=1){

cout << "invalid input" << endl;

return head;



}

ListNode* prep = NULL;

ListNode* curr = head;

ListNode* next = head->next;

int count = n-1;

while (count > 0 && next != NULL){



next = next->next;

count--;

}

if(count>0){

cout << "The linked list is not long enough" << endl;

return head;



}

while (next != NULL){



prep = curr;

curr = curr->next;

next = next->next;

}

if(prep == NULL) {

return head->next;



}

else{



prep->next = curr->next;

return head;



}

}


No comments:

Post a Comment