LInkedList
2016-05-18 07:28
387 查看
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
Given
Recursion
Sort a linked list using insertion sort.
When you are using dummy.next.next you'd better create a new reference node
Merge two sorted list
Reverse LinkedList
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); } }
Sort a linked list using insertion sort.
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; }
相关文章推荐
- IBM开发者社区:用 Eclipse 开发 Android 应用程序
- 平面分割问题
- 【华为OJ】【080-放苹果】
- 百度图片API
- awk of shell
- 【华为OJ】【079-查找组成一个偶数最接近的两个素数】
- 【有奖征文】走进VR开发世界(1)——我们离开发一款VR大作还有多远?
- Hanoi塔问题
- ActiveMQ入门实例
- 【华为OJ】【078-计算字符串的距离】
- 挂载本地硬盘的ISO镜像文件
- 如何使用eclipse开发android
- 【华为OJ】【077-迷宫问题】
- Laravel 5 性能优化技巧
- 要不要使用新技术
- 【华为OJ】【076-蛇形矩阵】
- 内存的堆分配和栈分配
- C++学习路线与推荐书籍
- linux 位置参数 特殊变量 read grep 变量赋值
- .NET Core 1.0 CentOS7 尝试