[leetcode 19 Remove Nth Node From End of List]week 13

来源:互联网 发布:黄金利多利空数据软件 编辑:程序博客网 时间:2024/06/05 04:44

一、题目

Given a linked list, remove the nth nodefrom the end of list and return its head.

For example,

 

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

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

Note: Given n willalways be valid. Try to do this in one pass.


二、代码

class Solution {

public:

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

   ListNode * first = head; 

   ListNode * second = head; 

   for(int i = 0;i < n;i++) 

       first = first->next; 

   if(first == NULL) 

       return head->next; 

while(first->next)

       first = first->next; 

       second = second->next; 

   } 

   second->next = second->next->next; 

   return head; 

}

};


三、思路

由于是移除从尾端数的第N个节点,设立两个指针,先让第一个指针移动n步,再同步移动知道第一个指针到达末尾已到达定位末端第N个节点的效果。若第一个指针移动n步后为空,则说明n>=链表长度,所以移除head即可返回head->next。若非空,则待定位成功后将第二个指针再移动一步。