LeetCode-24,19,160,142:
24.两两交换链表中节点
19.删除链表的倒数第N个节点
160.链表相交
142.环形链表Ⅱ
第一题:
使用递归法
class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null || head.next==null){
return head;
}
ListNode temp = head.next;
ListNode newhead = swapPairs(temp.next);
temp.next = head;
head.next = newhead;
return temp;
}
}
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
int length = 0;
int count = 0;
ListNode dummyhead = head;
ListNode cur = new ListNode(0);
cur.next = head;
while(dummyhead!=null){
dummyhead = dummyhead.next;
length++;
}
int index = length-n;
if(index==0){
return head.next;
}
if(length==1){
return null;
}
while(length>0){
cur = cur.next;
count++;
if(count==index){
if(cur.next!=null){
cur.next = cur.next.next;
break;
}
}
}
return head;
}
}
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA==null || headB==null){
return null;
}
ListNode cur1 = headA;
ListNode cur2 = headB;
while (cur1!=cur2){
if(cur1 !=null){
cur1 = cur1.next;
}else{
cur1 = headB;
}
if(cur2!=null){
cur2 = cur2.next;
}else{
cur2=headA;
}
}
return cur1;
}
}
思考:
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (true){
if(fast == null || fast.next == null){
return null;
}
slow = slow.next;
fast = fast.next.next;
if(slow==fast){
break;
}
}
fast = head;
while (slow!=fast){
slow = slow.next;
fast = fast.next;
}
return slow;
}
}