【LeetCode】19 - 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.
Solution 1: 重点在于one pass,以空间换取时间,使用vector<ListNode*>记录list的节点,每个指针指向一个链表节点,遍历一遍list算出size,通过下标计算(size-n)即可定位到需要删除的节点
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* removeNthFromEnd(ListNode* head, int n) { //runtime:12ms 12 vector<ListNode*> vec; 13 ListNode *temp=head; 14 int size=0; 15 while(temp){ 16 vec.push_back(temp); 17 temp=temp->next; 18 size++; 19 } 20 vec.push_back(NULL);//必不可少,否则如果删除的是倒数第一个元素的话下面的vec[i-1]->next=vec[i+1]中i+1溢出 21 int i=size-n; 22 if(i==0)//delete head 23 return head->next; 24 else{ 25 vec[i-1]->next=vec[i+1]; 26 return head; 27 } 28 } 29 };
Solution 2: 不需要额外的空间,当正数第n个移到链表尾时,head移到倒数第n个
1 class Solution { 2 public: 3 ListNode* removeNthFromEnd(ListNode* head, int n) { //runtime:4ms 4 ListNode *temp=head; 5 while(--n)temp=temp->next; 6 ListNode *del=head,*predel=NULL; 7 while(temp->next){ 8 temp=temp->next; 9 predel=del; 10 del=del->next; 11 } 12 if(predel==NULL)return head->next; 13 else{ 14 predel->next=del->next; 15 return head; 16 } 17 18 } 19 };