码迷,mamicode.com
首页 > 其他好文 > 详细

Remove Nth Node From End of List

时间:2015-07-22 22:32:31      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:

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;

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

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public ListNode removeNthFromEnd(ListNode head, int n) {
11         if( head == null )
12             return head;
13         //create a new head node so that we can always remove p.next
14         ListNode newHead = new ListNode(0);
15         newHead.next = head;
16         ListNode p = newHead;   //point to the previous node before to-be-deleted node
17         ListNode q = head;  //q - p = n;
18         int count = 1;  //to find the first satisfied q;
19         for( ; q.next!=null && count<n; count++, q = q.next);
20         //the to-be-deleted node exists
21         if(count == n ){
22             while( q.next != null ){
23                 p = p.next;
24                 q = q.next;
25             }
26             p.next = p.next.next;
27         }
28         return newHead.next;
29     }
30 }

 

Remove Nth Node From End of List

标签:

原文地址:http://www.cnblogs.com/hf-cherish/p/4668690.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!