Remove Nth Node From End of List
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.
思路:这道题从尾结点开始删除给定索引的值,然后再输出删除后的结点。我们可以使用两个指针pPost,pPre来解这道题,而且还要保存后面指针的前一结点为删除指定结点做准备。想让pPre先走n-1步,然后循环pPre和pPost共同起步行走,每一次之前都要把pPost保存下来,直到pPre->next为空循环结束。然后判断pTemp。
/** * 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) { if(head==NULL) return NULL; ListNode *pTemp=NULL; ListNode *pPre=head; ListNode *pPost=head; for(int i=0;i<n-1;i++) pPre=pPre->next; while(pPre->next!=NULL) { pTemp=pPost; pPre=pPre->next; pPost=pPost->next; } if(pTemp==NULL) { head=head->next; } else { pTemp->next=pPost->next; } return head; } };