Remove Nth Node From End of List
来源:互联网 发布:阿里云 证书被ios信任 编辑:程序博客网 时间:2024/06/07 05:44
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.
题目意思是给你一个链表,让你去除倒数第n个节点。
需要注意的是:
1.Try to do this in one pass.
2.使用双指针。
即让current先跑n个节点,然后再让next和current一起跑,当current后面没有节点了,则代表next的当前节点是需要删除的节点。
package leetcode;
public class RemoveNthNodeFromEndofList {
public ListNode removeNthFromEnd(ListNodehead, int n) {
int size = 0;
ListNode current =head;
ListNode next = head;
if (head ==null) return null;
for (inti = 0; i<n;i++){
//System.out.println(current.val);
current =current.next;
}
if(current ==null)
{
head = head.next;
next = null;
return head;
}
while (current.next !=null){
//System.out.println(current.val + " " + next.val);
current =current.next;
next =next.next;
}
//System.out.println(current.val + " " + next.val);
ListNode tmp = next.next.next;
next.next =tmp;
return head;
}
public staticvoid main(String[] args) {
// TODO Auto-generated method stub
ListNode head = new ListNode(1);
ListNode n1 = new ListNode(2);
ListNode n2 = new ListNode(3);
ListNode n3 = new ListNode(4);
ListNode end = new ListNode(5);
head.next =n1;
n1.next =n2;
n2.next =n3;
n3.next =end;
head = new RemoveNthNodeFromEndofList().removeNthFromEnd(head, 1);
while (head !=null){
System.out.print(head.val +" ");
head =head.next;
}
}
}
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node from End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- 安装MySQL-5.6失败
- 重复提交产生的情景
- 在Ubuntu上通过ssh远程挂载数莓派的共享目录(也可以是根目录)
- redis教程02
- 链表相邻元素翻转
- Remove Nth Node From End of List
- C++之父:C++ 的五个普遍误解
- POJ - 2724 Purifying Machine 二分图 最大匹配
- Winsock编程流程(1)-TCP/IP
- git忽略对已入库文件的修改
- 整合spring、redis
- TCP/IP, WebSocket 和 MQTT
- leetcode[104]:Maximum Depth of Binary Tree
- Java NIO:NIO概述