Rotate List
Given a list, rotate the list to the right by K -places, where K is non-negative.
For example:
Given 1->2->3->4->5->NULL
and k = 2
,
Return 4->5->1->2->3->NULL
.
/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution { PublicListNode Rotateright (ListNode head,intk) {ListNode First=Head; ListNode Slow=Head; ListNode Pre=Head; if(head==NULL|| head.next==NULL|| K==0){ returnHead; } intCount=1; while(pre.next!=NULL) {Pre=Pre.next; Count++; } if(k==count| | K%count==0) {//note k>list and K are multiples of listreturnHead; } k=k%count; for(inti=0;i<k;i++) { First=First.next; } while(first!=NULL) {Slow=Slow.next; First=First.next; } ListNode Res=slow; while(slow.next!=NULL) {Slow=Slow.next; } ListNode Temp=Head; while(temp!=Res) {Slow.next=temp; Temp=Temp.next; Slow=Slow.next; } Slow.next=NULL; returnRes; }}
Time O (n)
Remove Duplicates from Sorted List
Given a sorted linked list, delete all duplicates such this each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
Analysis: Two pointers traverse pre and current, one after the other
/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution { PublicListNode deleteduplicates (ListNode head) {if(head==NULL|| head.next==NULL){ returnHead; } ListNode Newhead=NewListNode (0); ListNode Res=Newhead; ListNode Pre=Head; ListNode Current=Head.next; while(current!=NULL){ if(pre.val!=current.val) {Newhead.next=NewListNode (Pre.val); Pre=Pre.next; Current=Current.next; Newhead=Newhead.next; }Else{ Current=Current.next; Pre=Pre.next; }} Newhead.next=Pre; returnRes.next; }}
Remove Duplicates from Sorted List
Given a sorted linked list, delete all nodes that has 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
.
Analysis: Add a recognizable flag to remove duplicate elements and a special case [1,1]or[2,2] .... Returned as null
/*** Definition for singly-linked list. * public class ListNode {* int val, * ListNode next; * ListNode (in T x) {val = x;}}*/ Public classSolution { PublicListNode deleteduplicates (ListNode head) {if(head==NULL|| head.next==NULL){ returnHead; } ListNode Newhead=NewListNode (0); ListNode Res=Newhead; ListNode Pre=Head; ListNode Current=Head.next; if(pre.val==current.val&¤t.next==NULL){ return NULL; } Booleanflag=true; while(current!=NULL){ if(pre.val!=current.val&& flag==true) {Newhead.next=NewListNode (Pre.val); Pre=Pre.next; Current=Current.next; Newhead=Newhead.next; }Else if(pre.val!=current.val&& flag==false) { current=Current.next; Pre=Pre.next; Flag=true; }Else if(pre.val==current.val) { Current=Current.next; Pre=Pre.next; Flag=false; } } if(flag==true) {Newhead.next=Pre; } returnRes.next; }}
Linklist Topic III