您的位置:首页 > 其它

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 
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: