61. 旋转链表
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head==null || head.next==null){
return head;
}
ListNode cur=head;
int n=0;
while(cur!=null){
n++;
cur=cur.next;
}
ListNode c=head;
for(int i=0;i<n-1;i++){
c=c.next;
}
c.next=head;
k=k%n;
ListNode res=head;
for(int i=0;i<n-k;i++){
cur=res;
res=res.next;
}
cur.next=null;
return res;
}
}
141. 环形链表
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null || head.next==null) return false;
ListNode slow=head;
ListNode fast=head;
while(fast!=null && fast.next!=null){
fast=fast.next.next;
slow=slow.next;
if(slow==fast){
return true;
}
}
return false;
}
}
83. 删除排序链表中的重复元素
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null || head.next==null) return head;
ListNode cur=head.next;
ListNode temp=head;
while(cur!=null){
if(cur.val==temp.val){
temp.next=temp.next.next;
cur=temp.next;
}else{
temp=cur;
cur=cur.next;
}
}
return head;
}
}
|