`
vvaaiinn
  • 浏览: 20936 次
  • 性别: Icon_minigender_1
  • 来自: 大连
文章分类
社区版块
存档分类
最新评论

LeetCode 19 Remove Nth Node From End of List 移除倒数第N个节点

 
阅读更多

题目:

Given a linked list, remove thenthnode 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:
Givennwill always be valid.
Try to do this in one pass.

翻译:

给你一个链表,移除倒数第N个节点。

思路:

这道题难度还行,就是一些细节的方面,首先可能链表就一个节点。其次有可能被删除的是第一个节点。最后就是删除该节点后节点的连接。

代码:

	 public ListNode removeNthFromEnd(ListNode head, int n) {
	         if(head==null||(head.next == null && n ==1))
	        	return null;
	        
	        ListNode p = head;
	        ListNode q = head;
	        ListNode pre = head;
	        while(n!=1)
	        {
	        	q = q.next;
	        	n--;
	        }
	        while(q.next!=null)
	        {
	            pre = p;
	        	q = q.next;
	        	p = p.next;
	        }
	        if(pre.next == p.next)
	            head = head.next;
	        else 
	            pre.next = p.next;

	        return head;
	        
	    }
我采用的办法是两个指针p,q,q先遍历到n-1的位置,然后两个指针同时向后遍历,直到q到结尾,此时p为应该删去的。同时来个指针指向p的前一个。

如果p 和pre 指向的是同一个节点,说明此时删去的是 第一个元素。因为上一部q.next==null,这是只要把头结点指向他下一个节点即可。

如果p和pre不等,则直接删除p

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics