/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/

方法:两次遍历算法
思路

我们注意到这个问题可以容易地简化成另一个问题:删除从列表开头数起的第 (L - n + 1)(L−n+1) 个结点,其中 LL 是列表的长度。只要我们找到列表的长度 LL,这个问题就很容易解决。

算法

首先我们将添加一个哑结点作为辅助,该结点位于列表头部。哑结点用来简化某些极端情况,例如列表中只含有一个结点,或需要删除列表的头部。在第一次遍历中,我们找出列表的长度 LL。然后设置一个指向哑结点的指针,并移动它遍历列表,直至它到达第 (L - n)(L−n) 个结*

点那里。我们把第 (L - n)(L−n) 个结点的 next 指针重新链接至第 (L - n + 2)(L−n+2) 个结点,完成这个算法。

class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
int length = 0;
ListNode first = head;
while (first != null){
length++;
first = first.next;
} length = length-n;
first = dummy;
while (length > 0){
length--;
first = first.next; }
first.next = first.next.next;
return dummy.next; }
}
// 以下为调试代码~~
public class MainClass {
public static int[] stringToIntegerArray(String input) {
input = input.trim();
input = input.substring(1, input.length() - 1);
if (input.length() == 0) {
return new int[0];
} String[] parts = input.split(",");
int[] output = new int[parts.length];
for(int index = 0; index < parts.length; index++) {
String part = parts[index].trim();
output[index] = Integer.parseInt(part);
}
return output;
} public static ListNode stringToListNode(String input) {
// Generate array from the input
int[] nodeValues = stringToIntegerArray(input); // Now convert that list into linked list
ListNode dummyRoot = new ListNode(0);
ListNode ptr = dummyRoot;
for(int item : nodeValues) {
ptr.next = new ListNode(item);
ptr = ptr.next;
}
return dummyRoot.next;
} public static String listNodeToString(ListNode node) {
if (node == null) {
return "[]";
} String result = "";
while (node != null) {
result += Integer.toString(node.val) + ", ";
node = node.next;
}
return "[" + result.substring(0, result.length() - 2) + "]";
} public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = in.readLine()) != null) {
ListNode head = stringToListNode(line);
line = in.readLine();
int n = Integer.parseInt(line); ListNode ret = new Solution().removeNthFromEnd(head, n); String out = listNodeToString(ret); System.out.print(out);
}
}
}
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
dummy = ListNode(0)
dummy.next = head
length = 0
first = head
while first:
length = length + 1
first = first.next
length = length - n
first = dummy
while length:
length = length -1
first = first.next first.next = first.next.next
return dummy.next def stringToListNode(input):
# Generate list from the input
numbers = json.loads(input) # Now convert that list into linked list
dummyRoot = ListNode(0)
ptr = dummyRoot
for number in numbers:
ptr.next = ListNode(number)
ptr = ptr.next ptr = dummyRoot.next
return ptr def stringToInt(input):
return int(input) def listNodeToString(node):
if not node:
return "[]" result = ""
while node:
result += str(node.val) + ", "
node = node.next
return "[" + result[:-2] + "]" def main():
import sys
def readlines():
for line in sys.stdin:
yield line.strip('\n')
lines = readlines()
while True:
try:
line = lines.next()
head = stringToListNode(line)
line = lines.next()
n = stringToInt(line) ret = Solution().removeNthFromEnd(head, n) out = listNodeToString(ret)
print out
except StopIteration:
break if __name__ == '__main__':
main()

  

leetcode-19:给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。的更多相关文章

  1. 数据结构:DHUOJ 删除链表的顺数及倒数第N个节点

    删除链表的顺数及倒数第N个节点 作者: turbo时间限制: 1S章节: DS:数组和链表 题目描述: 可使用以下代码,完成其中的removeNth函数,其中形参head指向无头结点单链表,n为要删除 ...

  2. 代码随想录第四天| 24. 两两交换链表中的节点 、19.删除链表的倒数第N个节点 、160.链表相交、142.环形链表II

    今天链表致死量 第一题 public static class ListNode { int val; ListNode next; ListNode() {} ListNode(int val) { ...

  3. 数据结构和算法之单向链表二:获取倒数第K个节点

    我们在做算法的时候或多或少都会遇到这样的问题,那就是我们需要获取某一个数据集的倒数或者正数第几个数据.那么今天我们来看一下这个问题,怎么去获取倒数第K个节点.我们拿到这个问题的时候自然而然会想到我们让 ...

  4. openquery链表删除时报错 “数据提供程序或其他服务返回 E_FAIL 状态”

    DELETE OPENQUERY (VERYEAST_COMPANY_MYSQL_CONN, 'SELECT * FROM company ') WHERE c_userid in(select c_ ...

  5. 有一个直方图,用一个整数数组表示,其中每列的宽度为1,求所给直方图包含的最大矩形面积。比如,对于直方图[2,7,9,4],它所包含的最大矩形的面积为14(即[7,9]包涵的7x2的矩形)。给定一个直方图A及它的总宽度n,请返回最大矩形面积。保证直方图宽度小于等于500。保证结果在int范围内。

    // ConsoleApplication5.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #include<vector> ...

  6. lintcode:Remove Nth Node From End of Lis 删除链表中倒数第n个节点

    题目: 删除链表中倒数第n个节点 给定一个链表,删除链表中倒数第n个节点,返回链表的头节点.  样例 给出链表1->2->3->4->5->null和 n = 2. 删除 ...

  7. 删除链表中倒数第n个节点

    给定一个链表,删除链表中倒数第n个节点,返回链表的头节点. 样例 给出链表1->2->3->4->5->null和 n = 2. 删除倒数第二个节点之后,这个链表将变成1 ...

  8. lintcode174 删除链表中倒数第n个节点

    删除链表中倒数第n个节点   给定一个链表,删除链表中倒数第n个节点,返回链表的头节点. 注意事项 链表中的节点个数大于等于n 您在真实的面试中是否遇到过这个题? Yes 样例 给出链表1->2 ...

  9. LintCode-174.删除链表中倒数第n个节点

    删除链表中倒数第n个节点 给定一个链表,删除链表中倒数第n个节点,返回链表的头节点. 注意事项 链表中的节点个数大于等于n 样例 给出链表 1->2->3->4->5-> ...

  10. 174. 删除链表中倒数第n个节点

    描述 笔记 数据 评测 给定一个链表,删除链表中倒数第n个节点,返回链表的头节点. 注意事项 链表中的节点个数大于等于n 您在真实的面试中是否遇到过这个题? Yes 样例 给出链表1->2-&g ...

随机推荐

  1. [Leetcode] 5279. Subtract the Product and Sum of Digits of an Integer

    class Solution { public int subtractProductAndSum(int n) { int productResult = 1; int sumResult = 0; ...

  2. C# 生成二维码(QR Code)

    参考:   C#通过ThoughtWorks.QRCode生成二维码(QR Code)   通过ThoughtWorks.QRCode(ThoughtWorks.QRCode.dll)来实现 1)   ...

  3. 记录一次排查使用HttpWebRequest发送请求的发生“基础连接已关闭:接收时发生错误”异常问题的过程

    描述:某次更新程序,需要给测试员MM测试,之前都是正常的,更新后给MM测试就报异常System.Net.WebException 基础连接已经关闭:接收时发生错误 -------> System ...

  4. SOTA激活函数学习

    除了之前较为流行的RELU激活函数,最近又新出了几个效果较好的激活函数 一.BERT激活函数 - GELU(gaussian error linear units)高斯误差线性单元 数学公式如下: X ...

  5. python 排序 桶排序

    算法思想: 桶排序将数组分到有限数量的桶里.然后每个桶里再分别排序(使用任何算法) 当要倍排序的数组内的数值时均匀分配的时候,桶排序使用线性时间O(n) 步骤: 根据最大值.最小值.桶内数据范围设定一 ...

  6. Bugku 多次

    网址:http://123.206.87.240:9004/1ndex.php?id=1 前言:bugku中一涉及多次注入的题 1.异或注入(判断字符是否被过滤) 0X00   很明显 注入点在id上 ...

  7. iOS批量添加SDK自动打包GUI工具

    背景 1.之前在给游戏开发商做SDK接入技术支持的时候,很多cp对iOS开发技术并不是很了解,对接SDK和打包都很迷糊,虽然我们根据他们的开发环境输出了不同的插件解决方案,这一步已经把接入SDK的复杂 ...

  8. OpenInstall实现APP无邀请码推广

    1.登录OpenInstall网站,这里会为你创建一个AppKey,而这个东西在web页面会用到. 2.在推广页面中加入推广下载. <script type="text/javascr ...

  9. 安装Python,输入pip命令报错———pip Fatal error in launcher: Unable to create process using

    今天把Python的安装位置也从C盘剪切到了D盘, 然后修改了Path环境变量中对应的盘符:D:\Python27\;D:\Python27\Scripts; 不管是在哪个目录,Python可以执行了 ...

  10. msyql error: Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A

    mysql> use mydb Reading table information for completion of table and column names You can turn o ...