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

leetcode 19 Remove Nth Node From End of List

时间:2015-05-27 14:07:14      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:leetcode 19   remove nth node from   java   linkedlist基本用法   

Remove Nth Node From End of List Total Accepted: 54131 Total Submissions: 197763  
Given a linked list, remove the n‘th 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.(对于给定的n将永远有效)
Try to do this in one pass.

Hide Tags: Linked List, Two Pointers

删除链表的倒数第n个元素


思路一:先统计链表中节点的个数,然后再计算出倒数第n个是正数第多少个,再进行移除即可,但这样的话就不满足one pass的要求。(放弃)

思路二:p先跑n个节点,随后p,q一起跑,待p跑到链表尾部时,q节点刚好跑到需要移除的节点的前节点上, 然后进行跳过处理即可

代码如下:


/**
 * 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) 
    {
		ListNode temp = new ListNode(0);
		temp.next=head;
		//将两节点置于同一起始点,即head的前节点,均为空。
		ListNode p=temp;
		ListNode q=temp;
		if(head==null)
		{
			return null;
		}
		/**
		 * p先跑n个节点,随后p,q一起跑
		 * 待p跑到链表尾部时,q节点刚好跑到需要移除的节点的前节点上
		 * 然后进行跳过处理即可
		 */
		for (int i = 0; i < n; i++)
		{
			p=p.next;
		}
		while (p.next!=null)
		{
			p=p.next;
			q=q.next;	
		}
		q.next=q.next.next;
		
		return temp.next;
    }
}


链表题心得:链表头的处理,通常是建立一个不用的节点,使其下一级节点指向头节点

		ListNode temp = new ListNode(0);
		temp.next=head;

然后真正的头在temp.next里面,这样代码要少了单独处理头的那部分



leetcode 19 Remove Nth Node From End of List

标签:leetcode 19   remove nth node from   java   linkedlist基本用法   

原文地址:http://blog.csdn.net/zzc8265020/article/details/46044345

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