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 class Solution { public ListNode rotateRight(ListNode head, int k) { ListNode first=head; ListNode slow=head; ListNode pre=head; if(head==null||head.next==null||k==0){ return head; } int count=1; while(pre.next!=null){ pre=pre.next; count++; } if(k==count||k%count==0){ //注意k>list AND k为list的倍数 return head; } k=k%count; for(int i=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; return res; } }
time O(n)
Remove Duplicates from Sorted List
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
分析:两个指针遍历pre和current,一前一后
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode deleteDuplicates(ListNode head) { if(head==null||head.next==null){ return head; } ListNode newhead=new ListNode(0); ListNode res=newhead; ListNode pre=head; ListNode current=head.next; while(current!=null){ if(pre.val!=current.val){ newhead.next=new ListNode(pre.val); pre=pre.next; current=current.next; newhead=newhead.next; }else{ current=current.next; pre=pre.next; } } newhead.next=pre; return res.next; } }
Remove Duplicates from Sorted List
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
.
分析:加一个可识别的flag去掉重复元素以及一个特例[1,1]or[2,2]....返回为null
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode deleteDuplicates(ListNode head) { if(head==null||head.next==null){ return head; } ListNode newhead=new ListNode(0); ListNode res=newhead; ListNode pre=head; ListNode current=head.next; if(pre.val==current.val&¤t.next==null){ return null; } boolean flag=true; while(current!=null){ if(pre.val!=current.val&& flag==true){ newhead.next=new ListNode(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; } return res.next; } }
时间: 2024-10-05 23:58:24