LInkedList
来源:互联网 发布:Js识别 key value 编辑:程序博客网 时间:2024/06/11 09:47
When using two pointers, do not use
fast.next != nullfast may be null
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
Recursion
public ListNode deleteDuplicates2(ListNode head) { if(head == null || head.next == null){ return head; } int val = head.val; ListNode next = head.next; if(next.val != val){ head.next = deleteDuplicates(next); return head; }else{ while(next != null && next.val == val){ next = next.next; } return deleteDuplicates(next); } }
public static ListNode insertionSortList(ListNode head) {if( head == null ){ return head; } ListNode dummy = new ListNode(0); //new starter of the sorted list ListNode cur = head; //the node will be inserted ListNode pre = dummy; //insert node between pre and pre.next ListNode next = null; //the next node will be inserted //not the end of input list while( cur != null ){ next = cur.next; //find the right place to insert while( pre.next != null && pre.next.val < cur.val ){ pre = pre.next; } //insert between pre and pre.next cur.next = pre.next; pre.next = cur; pre = dummy; cur = next; } return dummy.next; }
When you are using dummy.next.next you'd better create a new reference node
Merge two sorted list
//This function is from Merge Two Sorted Lists.public static ListNode merge(ListNode l1,ListNode l2){ if(l1==null) return l2; if(l2==null) return l1; if(l1.val<l2.val){ l1.next=merge(l1.next,l2); return l1; }else{ l2.next=merge(l1,l2.next); return l2; }}
Reverse LinkedList
public static ListNode reverseListDummy(ListNode head){if(head == null){return head;}ListNode dummy = new ListNode(-1);ListNode cur = head;while(cur != null){ListNode temp = cur.next;cur.next = dummy.next;dummy.next = cur;cur = temp;}return dummy.next;}
0 0
- LinkedList
- LinkedList
- LinkedList
- LinkedList
- LinkedList
- LinkedList
- LinkedList
- LinkedList
- LinkedList
- LinkedList
- LinkedList
- LinkedList
- LinkedList
- LinkedList
- LinkedList
- LinkedList
- LinkedList
- LinkedList
- 陶哲轩实分析-第6章-序列的极限
- awk of shell
- 内存管理之slab分配器
- 【华为OJ】【079-查找组成一个偶数最接近的两个素数】
- Unlock files in batch
- LInkedList
- IBM开发者社区:用 Eclipse 开发 Android 应用程序
- 平面分割问题
- 【华为OJ】【080-放苹果】
- 走进VR开发世界(2)——一些VR延迟优化方法
- 教你写一个炫酷的Material Design 风格的登录和注册页面
- 走进VR开发世界(3)——虚拟现实游戏的十大误区
- 走进VR开发世界(4)——走进VR游戏开发的世界
- 走进VR开发世界(5)—— 使用Cocos开发一款简单的3D VR抓钱游戏