LeetCode-19. Remove Nth Node From End of List
来源:互联网 发布:淘宝发快递一般多少钱 编辑:程序博客网 时间:2024/06/04 00:22
一、问题描述
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.
二、解题思路
思路一:遍历两遍链表,第一遍计算链表的总长度,第二遍定位需要移除的链表元素。
思路二:遍历一遍链表,定义两个变量first和second,分别指向链表不同的元素,并且满足first-second=n,然后first和second不断自增,当first指向的元素的下一个是null是,second就指向了目标元素的上一个,然后执行移除操作。
三、代码
思路一:
/** * 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) { ListNode result=new ListNode(0);//如果result直接指向head,需要考虑当链表的长度等于n时,即移除第一个链表元素时这种情况。 result.next=head; if(head==null || n<=0) return head; int count=0; while(head!=null){ head=head.next; count++; } int i=0; head=result; while(true){ if(i==count-n){ head.next=head.next.next; break; } head=head.next; i++; } return result.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) { ListNode result=new ListNode(0); result.next=head; if(head==null || n<=0) return head; ListNode first=result; ListNode second=result; for(int i=0;i<n;i++){ first=first.next; } while(first.next!=null){//如果这里判断的是first!=null,则前面first需要移动n+1 first=first.next; second=second.next; } second.next=second.next.next; return result.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
- ls和rm管道符删除文件
- Netty源码解读------------客户端接入绑定(二)
- Could not Open Install.Log File解决方法
- java线程状态——死锁
- C#中调用CMD命令行截取输出流的范例
- LeetCode-19. Remove Nth Node From End of List
- Android之源码之模块编译调试
- WebView交互传递json字符串并解析
- servlet的一个小项目(四)
- 继续自己的第一个swift项目的奋斗之路!
- TFS 测试用例导入、导出工具
- Hibernate入门
- Android的开机启动流程概述
- ssm整合