您的位置:首页 > Web前端 > Node.js

Remove Nth Node From End of List

2015-07-22 21:26 645 查看

1. Problem

去掉链表的倒数第n个节点,并返回链表头。一次遍历完成

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.


2. Solution

用两个指针:

p:指向可能的待删节点的前一个节点;

q:q-p = n;

为了方便处理,在链表前加上一个空节点。代码如下:

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if( head == null )
return head;
//create a new head node so that we can always remove p.next
ListNode newHead = new ListNode(0);
newHead.next = head;
ListNode p = newHead;   //point to the previous node before to-be-deleted node
ListNode q = head;  //q - p = n;
int count = 1;  //to find the first satisfied q;
for( ; q.next!=null && count<n; count++, q = q.next);
//the to-be-deleted node exists
if(count == n ){
while( q.next != null ){
p = p.next;
q = q.next;
}
p.next = p.next.next;
}
return newHead.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: