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

Remove Nth Node From End of List

时间:2015-02-01 13:25:30      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

大概思路:

1)用p,q两个指针来记录2个位置,p,q初始化为head;

2)然后p先不动,q向后移动n个位置;

3)接着p,q以同样的步伐一起向链表尾部移动,直到q到达链表尾部,即q.next==null;

4)此时p是待删除节点的前驱,修改p.next即可。

这里一个细节要考虑,若n等于节点数,即删除倒数第n个也就是第1个节点,那么在第2)步q会移动到尾部节点下一个位置即q==null,所以移动时加个判断即可。

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode p = head;
        ListNode q = head;
        while(n!=0){
            q = q.next;
            //如果q==null说明n==List.length,即删除第一个节点
            if(q==null){
                return head.next;
            }
            n--;
        }
        while(q.next!=null){
            p = p.next;
            q = q.next;
        }
        ListNode temp = p.next;
        p.next = temp.next;
        return head;
    }
}

 

Remove Nth Node From End of List

标签:

原文地址:http://www.cnblogs.com/mrpod2g/p/4265356.html

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