leetcode-19 Remove Nth Node From End of List
来源:互联网 发布:彩票模拟关注软件 编辑:程序博客网 时间:2024/06/14 07:33
Question:
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, andn = 2.
After removing the second node from the end, the linked list becomes1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
从前遍历一遍链表,求出链表的长度,并把节点存储在ArrayList数据结构中,直接访问ArrayList中的节点即可。
java中,除了主类型(int,String,float等) 之外的类型的对象,用等号等于引用,只要改变了一边的值,另一边的也会变化。而主类型的对象用等号是直接赋值。
java代码如下:
/**
* 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) {
List<ListNode> nodes = new ArrayList();
ListNode cur = head;
int len = 0;
while(cur != null){
nodes.add(cur);
cur = cur.next;
len ++;
}
if(len - n == 0){
return head.next;
}
ListNode prev = nodes.get(len - n - 1);
if(len - n + 1 >= len){
prev.next = null;
return head;
}
ListNode next = nodes.get(len - n + 1);
prev.next = next;
return head;
}
}
- [Leetcode]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, Easy] 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 Solutions
- 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 | #19 Remove Nth Node From End of List
- leetcode.19----------Remove Nth Node From End of List
- [Leetcode 19, Easy] 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 19 Remove Nth Node From End of List
- leetcode 19 Remove Nth Node From End of List
- leetcode oj java Add Strings
- Windows下mysql忘记root密码的解决方法
- 实现鼠标拖拉图片交换图片位置
- 冒泡排序中数据交换的次数
- 写在前面的话
- leetcode-19 Remove Nth Node From End of List
- 【Tyvj2046】掷骰子
- C语言实验——数组逆序
- masterJ2EE篇005——Servlet url-pattern详解
- windows 7系统安装与配置Tomcat服务器环境
- hdoj-1241【Oil Deposits】
- C语言实验——数日子
- SSL、openSSL、CA
- 我的vim的vimrc配置文件,保存用 - 飞在天空的鱼 - 博客频道