博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【LeetCode从零单排】No19.RemoveNthNodeFromEndofList
阅读量:7219 次
发布时间:2019-06-29

本文共 1136 字,大约阅读时间需要 3 分钟。

题目

       
这是道链表的简单应用题目,删除从结尾数第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.

代码

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */ public class Solution {    public ListNode removeNthFromEnd(ListNode head, int n) {        ListNode faster = head;	    ListNode slower = head;	    while (n > 0 && faster != null) {	        faster = faster.next;	        n--;	    }	    // Check if has only node	    if (faster == null) return head.next; 	    while (faster.next != null) {	        faster = faster.next;	        slower = slower.next;	    }	    // Remove slower.next which is the nth form the end	    slower.next = slower.next.next;	    return head;    }}
代码下载:

/********************************

* 本文来自博客  “李博Garvin“

* 转载请标明出处:

******************************************/

你可能感兴趣的文章
SVN
查看>>
C语言编程写的一个http下载程序(王德仙)2012-04-08
查看>>
CCF201409-3 字符串匹配(100分)
查看>>
UVALive2203 UVa10042 Smith Numbers【质因数分解+素数判定+数位之和】
查看>>
Project Euler Problem 9: Special Pythagorean triplet
查看>>
HDU5701 中位数计数【中位数】
查看>>
Python 深浅拷贝 (Shallow copy and Deep copy in Python)
查看>>
Axure
查看>>
屏幕截取工具
查看>>
C语言第七次作业---要死了----
查看>>
Jquery事件绑定冲突
查看>>
偶现bug如何处理?
查看>>
yum命令简介
查看>>
【Udacity】朴素贝叶斯
查看>>
看漫画,学 Redux
查看>>
Spark Streaming揭秘 Day19 架构设计和运行机制
查看>>
【转载】WinCE OAL中的电源管理函数
查看>>
【iOS】Objective-C简约而不简单的单例模式
查看>>
Java实现扫码二维码登录
查看>>
python之字符串的操作和使用
查看>>