LeetCode#19. Remove Nth Node From End of List
来源:互联网 发布:p4vasp windows 编辑:程序博客网 时间:2024/06/04 18:27
- 题目:删除链表倒数第n个元素
- 难度:Medium
- 思路:这道题与查找倒数第n个结点类似,因为我们需要删除倒数第n个结点,所以我们需要找到倒数第n个结点的前一个节点(定义个fast和一个slow两个指针,fast先走n步)
- 代码:
不给链表加上一个头结点
public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { if(head == null || n == 0){ return null; } if(head.next == null){ if(n == 1){ return null; }else{ return head; } } ListNode slow = head; ListNode fast = head; //fast指针先走n步 while(fast != null && n > 0){ fast = fast.next; n--; } //如果n大于链表节点个数,则直接返回链表 if(n > 0){ return head; } //这个if判断是删除结点正好是头结点 if(fast == null && n == 0){ slow = new ListNode(head.next.val); slow.next = head.next.next; return slow; } //两个节点同时从当前位置走,直到fast指针走到最后一个节点,这时slow指向待删除节点的前一个 while(fast != null && fast.next != null){ fast = fast.next; slow = slow.next; } if(slow.next != null){ ListNode delete = slow.next; slow.next = delete.next; } return head; }}
给链表加上头结点
public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { if(head == null || n == 0){ return null; } ListNode start = new ListNode(0); ListNode slow = start; ListNode fast = start; slow.next = head; //fast指针先走n步 while(fast != null && n > 0){ fast = fast.next; n--; } //如果n大于链表节点个数,则直接返回链表 if(n > 0){ return head; } //找到待删除节点的上一个节点 while(fast != null && fast.next != null){ fast = fast.next; slow = slow.next; } slow.next = slow.next.next; return start.next; }}
阅读全文
0 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
- Android 初学者入门(一个最简单的应用程序)
- Hibernate框架-1对1关联
- 2017上海金马五校程序设计竞赛部分题解
- linux下误操作startx命令后,在登录界面进不去解决办法
- 【工作流】Jbpm(一)——认识jbpm
- LeetCode#19. Remove Nth Node From End of List
- 将Eclipse中的Web项目部署到Tomcat
- 百度作业帮 生成随机红包算法
- hadoop 常见问题
- ConcurrentHashMap源码分析_JDK1.8版本
- 移动生活
- 给初学者的 RxJava2.0 教程 (九)
- DNS服务器配置和测试
- H5小白入门笔记(1)