题目:
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.
Note:
Given n will always be valid.
Try to do this in one pass.
代码1:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *removeNthFromEnd(ListNode *head, int n) { ListNode *FirstPtr,*SecondPtr; FirstPtr=SecondPtr=head; int count=0; while(FirstPtr!=NULL){ FirstPtr=FirstPtr->next; count++; } if(count==n)return head->next; while(count-n>1){ SecondPtr=SecondPtr->next; count--; } ListNode *to_delete=SecondPtr->next; SecondPtr->next=SecondPtr->next->next; delete to_delete; return head; } };
解题思路2:建立一个位于头节点之前的节点(该节点的next域指向头节点),设立两个指向该节点的指针,让第一个指针先往后走n步,然后两个指针一起向后走直到最后一个节点,此时第二个指针所在位置的下一个节点就是需要删除的节点。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *removeNthFromEnd(ListNode *head, int n) { ListNode Forehead(0); Forehead.next=head; ListNode *FirstPtr,*SecondPtr; FirstPtr=SecondPtr=&Forehead; while(n--){ FirstPtr=FirstPtr->next; }; while(FirstPtr->next){ FirstPtr=FirstPtr->next; SecondPtr=SecondPtr->next; } ListNode *to_delete=SecondPtr->next; SecondPtr->next=SecondPtr->next->next; delete to_delete; return Forehead.next; } };