/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode swapPairs(ListNode head) { ListNode dummyhead = new ListNode(-1); dummyhead.next = head; if(head==null||head.next==null) return head; ListNode temp; ListNode firstnode; ListNode secondnode; ListNode curr = dummyhead; while(curr.next!=null&&curr.next.next!=null) { temp = curr.next.next.next; firstnode = curr.next; secondnode = curr.next.next; curr.next = secondnode; secondnode.next = firstnode; firstnode.next = temp; curr = firstnode; } return dummyhead.next; } } |
没有想到可以使用虚拟头结点,并且自己本来的思路不够简洁,值得二刷
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummyhead = new ListNode(); dummyhead.next = head; ListNode slow = dummyhead; ListNode fast = dummyhead; if(head.next==null&&n==1) return null; for(int i=0;i<n+1;i++) { fast = fast.next; } while(fast!=null) { slow=slow.next; fast=fast.next; } slow.next=slow.next.next; return dummyhead.next; } } |
逐渐养成了构造虚拟头结点的思维,但是具体的解题思路还是不如代码随想录的答案简洁高效,可二刷。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { ListNode a = headA; ListNode b = headB; int lenA=0,lenB=0; while(a!=null) { lenA++; a=a.next; } while(b!=null) { lenB++; b=b.next; } a=headA; b=headB; if(lenB>lenA) { ListNode tem = a; a = b; b = tem; int temp = lenA; lenA = lenB; lenB = temp; } int gap = lenA-lenB; while(gap>0) { a=a.next; gap--; } while(a!=null) { if(a==b) { return a; } a=a.next; b=b.next; } return null;
} } |
这道题我自己是完全没有思路的,值得二刷,其中让a是最长链表这个思想,应该练习,让代码更简洁
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode detectCycle(ListNode head) { ListNode fast=head; ListNode slow=head; while(fast!=null&&fast.next!=null) { fast=fast.next.next; slow=slow.next; if(fast==slow)//有环 { ListNode l1 = head; ListNode l2 = fast; while(l1!=l2) { l1=l1.next; l2=l2.next; } return l1; } } return null;
} } |
这道题目的分析过程很难,感觉只是听懂了,自己做还是想不到这个思路,还是需要了解暴力算法打个底