Given A linked list, remove the nth node from the end of the list and return its head.
For example,
1->2->3->4->5 N = 2. 1->2->3->5.
Note:
Given n would always be valid.
Try to do the in one pass.
Algorithm: 1 prepare two pointers first, Second2 let FISRT walk n step 3 let fisrt and second go at the same time until you meet the end 4 to use a temp pointer to record second the previous node, used to delete second.
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * listnode (int x): Val (x), Next (NULL) {} *}; */class Soluti On {public: listnode* removenthfromend (listnode* head, int n) { ListNode *first = head, *second = head; ListNode *temp = second; for (int i = 0; i < n; i++) {First = First, next; } while (first) {First = First, next; temp = second; Second = second Next; } if (second = = head) { head = head-next ; } else { temp, next = Second next; } return head; };
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode:remove Nth Node from End of List