首页 > 其他 > 详细

LeetCode(19): Remove Nth Node From End of List

时间:2016-01-13 21:30:41      阅读:103      评论:0      收藏:0      [点我收藏+]

Remove Nth Node From End of List: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.

题意:删除给定链表倒数第n个结点。

思路:其实本题比较常规的思路是先遍历链表求得链表的长度,然后在进行删除操作。另外一种思路是定义两个指针left和right,right先移动n步,如果right为null,则表示要删除的是头结点,此时直接返回head.next即可。如果first指针不为null,则两个指针一起移动,直到right为最后一个结点为止,left指向的即是要删除结点的前一个结点,可以直接执行left.next=left.next.next操作即可删除倒数第n个结点。

代码:

public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head==null) return null;
        ListNode p = head;
        ListNode q = head;
        
        for(int i=0;i<n;i++){
            q=q.next;
        }
        if(q==null){
            head = head.next;
            p = null;
            return head;
        }
        while(q.next!=null){
            p = p.next;
            q = q.next;
        }
        ListNode temp = p.next.next;
        p.next = temp;
        return head;
         
    }

LeetCode(19): Remove Nth Node From End of List

原文:http://www.cnblogs.com/Lewisr/p/5128242.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!