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

leetcode_19_Remove Nth Node From End of List

时间:2015-02-03 11:06:08      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:链表   移动   倒数第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.

思路:

先让p指向head,p往后移动n个节点,然后让q指向head,p和q一起后移直至p指向最后一个结点,则q指向的结点即是倒数第n个结点。当然,倒数第len(链表的长度)个结点是一个特殊情况,直接head=head.next即可。

代码:

public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head==null)
        	return head;
        ListNode pListNode=head,qListNode=head;
        int len=0;
        while(pListNode!=null)
        {
        	len++;
        	pListNode=pListNode.next;
        }
        if(n==len)
        {
        	head=head.next;
        	return head;
        }
        pListNode=head;
        for(int i=0;i<n;i++)
        {
        	qListNode=qListNode.next;
        	if (qListNode==null)
        		break;
        }
        	
        while(qListNode!=null&&qListNode.next!=null)
        {
        	pListNode=pListNode.next;
        	qListNode=qListNode.next;
        }
        qListNode=pListNode.next;
        pListNode.next=qListNode.next;
        return head;
    }


结果:

技术分享

leetcode_19_Remove Nth Node From End of List

标签:链表   移动   倒数第n个结点   

原文地址:http://blog.csdn.net/mnmlist/article/details/43446561

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