博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode 19 Remove Nth Node From End of List
阅读量:5906 次
发布时间:2019-06-19

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

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.

解决方案:

Because the linked list have no knowledge about the previous nodes, we have to provide such information.

The difference between the final node and the to-be-delete node is N, hence we can utilize this information.

•front pointer points to the node which is N step away from the to-be-delete node
•rear pointer points to the to-be-delete node.

The algorithms is described as below:

•First driving front pointer N step forward.
•Secondly, move the 2 pointers 1 step ahead till the front pointer reach the end simultaneously, which will cause the rear pointer points to the previous node of the to-be-delete node.
Finally, jump the rear->next node by rear->next = rear->next->next.

下面的代码稍微有一个疑问:

class Solution {public:    ListNode *removeNthFromEnd(ListNode *head, int n) {        ListNode new_head(-1);        new_head.next = head;        ListNode *front = &new_head, *rear = &new_head;        for (int i = 0; i < n; i++)            front = front->next;        while (front->next != NULL) {            front = front->next;            rear = rear->next;        }        ListNode *tmp = rear->next;        rear->next = rear->next->next;        delete tmp;        head = new_head.next;        return head;    }};

python解决方案:

# Definition for singly-linked list.# class ListNode:#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution:    # @param {ListNode} head    # @param {integer} n    # @return {ListNode}    def removeNthFromEnd(self, head, n):        dummyHead = ListNode(0)        dummyHead.next = head        slow = fast = dummyHead        for i in range(n):            fast = fast.next        while fast and fast.next:            fast = fast.next            slow = slow.next        slow.next = slow.next.next        return dummyHead.next

转载地址:http://xajpx.baihongyu.com/

你可能感兴趣的文章
linux基础命令 head
查看>>
objective c:import和include的区别, ""和<>区别
查看>>
The Shared folder with you
查看>>
sax方式解析XML学习笔记
查看>>
Springboot配置(上)
查看>>
java--Eclipse for mac 代码提示(代码助手,代码联想)快捷键修改
查看>>
left join on/right join on/inner join on/full join on连接
查看>>
template.helper 多参数
查看>>
Android 四大组件之一(Activity)
查看>>
扫描(一)
查看>>
Centos7安装rabbitmq server 3.6.0
查看>>
iostat命令学习
查看>>
html video的url更新,自动清缓存
查看>>
【11】ajax请求后台接口数据与返回值处理js写法
查看>>
Python菜鸟之路:Jquery Ajax的使用
查看>>
LeetCode算法题-Maximum Depth of Binary Tree
查看>>
Cox 教学视频5
查看>>
使用ffmpeg实现对h264视频解码 -- (实现了一个易于使用的c++封装库)
查看>>
flink watermark介绍
查看>>
Android Xutils 框架
查看>>