[LeetCode]19. Remove Nth Node From End of List

栏目: 编程工具 · 发布时间: 6年前

内容简介:上面的方法需要遍历两次链表也可以一次遍历出

Given a linked list, remove the n-th node from the end of list and

return its head.

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.

Follow up:

Could you do this in one pass?

链表操作的题,比较简单,主要主要Bug Free

public ListNode removeNthFromEnd(ListNode head, int n) {
    int len=0;
    ListNode cur=head;
    while(cur!=null){
        len++;
        cur=cur.next;
    }
    len=len-n;
    ListNode trueHead=new ListNode(0);
    trueHead.next=head;
    cur=trueHead;
    while(len>=1){
        cur=cur.next;
        len--;
    }
    cur.next=cur.next.next;
    return trueHead.next;
}

上面的方法需要遍历两次链表

也可以一次遍历出

public ListNode removeNthFromEnd(ListNode head, int n) {
    ListNode trueHead=new ListNode(0);
    trueHead.next=head;
    ListNode first=trueHead;
    ListNode second=trueHead;
    for(int i=0;i<n;i++) first=first.next;
    while(first.next!=null){
        first=first.next;
        second=second.next;
    }
    second.next=second.next.next;
    return trueHead.next;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

编程珠玑(续)(修订版)

编程珠玑(续)(修订版)

【美】Jon Bentley 乔恩•本特利 / 钱丽艳、刘田 / 人民邮电出版社 / 2015-2 / CNY 35.00

历史上最伟大的计算机科学著作之一 融深邃思想、实战技术与趣味轶事于一炉的奇书 带你真正领略计算机科学之美 多年以来,当程序员们推选出最心爱的计算机图书时,《编程珠玑》总是位于前列。正如自然界里珍珠出自细沙对牡蛎的磨砺,计算机科学大师Jon Bentley以其独有的洞察力和创造力,从磨砺程序员的实际问题中凝结出一篇篇不朽的编程“珠玑”,成为世界计算机界名刊《ACM通讯》历史上最受欢......一起来看看 《编程珠玑(续)(修订版)》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具