19. Remove Nth Node From End of List
来源:互联网 发布:win7 传奇3 数据库 编辑:程序博客网 时间:2024/06/04 23:35
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个位置,这样快指针变成null的时候慢指针就指到了要删掉的位置,这个新方法其实比较好。
这里用的方法是把所有节点存起来orz……当年怎么想到这么有创意的方法……然后把上一个指到后一个……
/** * 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> node = new ArrayList<ListNode> (); int count=0; for(ListNode a=head;a!=null;a=a.next){ count++; node.add(a); } // if(n==1&&count>=2)node.get(count-2).next=null; if(n==count)head=head.next; if(1<=n&&n<count)node.get(count-n-1).next=node.get(count-n).next; return head; }}
0 0
- 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
- 关于HTML初识 笔记
- 用Python直接写UTF-8文本文件
- python数据类型--序列
- android开发步步为营之97:几种常用的android图片内存优化方法避免OOM
- Problem D: 求最高同学位置
- 19. Remove Nth Node From End of List
- 58. Length of Last Word
- mac与windows系统的互相访问
- python数据类型--字典
- HDU 2955 Robberies(01背包)(动态规划)
- 299. Bulls and Cows
- BZOJ1901: Zju2112 Dynamic Rankings
- 将任意类型转为number类型
- xcode7编译老版本程序时提示错误的处理方法