【Leetcode】19. Remove Nth Node From End of List
来源:互联网 发布:云计算与大数据 编辑:程序博客网 时间:2024/06/05 00:29
方法一:
思路:
(1)若链表为空,直接返回null。
(2)求链表的长度len。
(3)若n==len,则删除的是第一个节点,直接删除后返回即可。
(4)从头开始遍历链表,找到待删除节点cur,并用pre记录其前驱结点。
(5)若pre不为空,说明删除的不是第一个节点,直接置pre.next=cur.next即可。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution {public ListNode removeNthFromEnd(ListNode head, int n) {if (head == null)return null;ListNode cur = head, pre = null;int len = 0;while (cur != null) {cur = cur.next;len++;}if (n == len) {head = head.next;return head;}cur = head;for (int i = 0; i < len - n; i++) {pre = cur;cur = cur.next;}if (pre != null) pre.next = cur.next;return head;}}
Runtime:15ms
方法二:双指针
思路:
(1)双指针:设置两个指针first跟second。
(2)first指针先移动n步。
(3)若first指针为空,则表示要删除的是头节点,此时直接返回head->next即可。
(4)若first指针不为空,则将两个指针一起移动,直到first指针指向最后一个节点,令second->next=second->next->next即可。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution {public ListNode removeNthFromEnd(ListNode head, int n) {if (head == null)return head;ListNode first = head, second = head;for (int i = 0; i < n; i++)first = first.next;if (first != null) {while (first.next != null) {first = first.next;second = second.next;}second.next = second.next.next;}elsehead = head.next;return head;}}
Runtime:15ms
1 0
- 19. Remove Nth Node From End of List leetcode list
- [LeetCode]19.Remove Nth Node From End of List
- LeetCode 19. Remove Nth Node From End of List
- 19. Remove Nth Node From End of List Leetcode Python
- LeetCode --- 19. Remove Nth Node From End of List
- LeetCode 19.Remove Nth Node From End of List
- [Leetcode] 19. Remove Nth Node From End of List
- [leetcode] 19.Remove Nth Node From End of List
- <LeetCode OJ> 19. Remove Nth Node From End of List
- 19. Remove Nth Node From End of List LeetCode
- leetcode 19. Remove Nth Node From End of List
- [LeetCode OJ] 19. Remove Nth Node From End of List
- LeetCode 19. Remove Nth Node From End of List
- Leetcode:19. Remove Nth Node From End of List(JAVA)
- leetcode 19. Remove Nth Node From End of List
- Leetcode 19. Remove Nth Node From End of List
- 【LeetCode】19. Remove Nth Node From End of List
- leetcode 19.Remove Nth Node From End of List
- 自动安装二进制mysql
- mysql安装出现error Nr.1045
- 第十五周项目二——用哈希法组织关键字
- 使用了fresco和recylerView的下拉刷新的Apk
- 第十六周项目1-(3)验证算法冒泡排序
- 【Leetcode】19. Remove Nth Node From End of List
- IOS8以上或以下 presentViewController 背景不透明解决办法
- qt常用的基本属性设置
- 三维点云拼接 标记点拼接 SVD分解法
- js $.each用return 后为什么后面的js还可以执行
- Microsoft Office Professional Plus 2007 简体中文版
- 第十六周项目7—基数排序
- 用font-spider释放字体文件大小,只取所需!
- 避免同一activity下 多个fragment 切换时重复执行onCreateView方法