HF_Cherish

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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 }

 

posted on 2015-07-22 21:26  HF_Cherish  阅读(189)  评论(0编辑  收藏  举报