链表|160.相交链表234.回文指针141环形链表

相交链表

点击查看代码
/**
 * 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;
        int a = 0;
        while(A != null){
            A = A.next;
            a += 1;
        }
        ListNode B = headB;
        int b = 0;
        while(B != null){
            B = B.next;
            b += 1;
        }
        if(a > b){
            int c = a - b;
            while(c != 0){
                headA = headA.next;
                c--;
            }
        }
        else{
            int c = b - a;
            while(c != 0){
                headB = headB.next;
                c--;
            }
        }
        while(headA != headB){
            headA = headA.next;
            headB = headB.next;
        }
        return headA;
    }
}

234.回文链表

快慢指针找中点。
class Solution {
public boolean isPalindrome(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
}
ListNode pre = null;
ListNode cur = slow;
while(cur != null){
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
while(pre != null){
if(pre.val != head.val) return false;
pre = pre.next;
head = head.next;
}
return true;
}
}

141环形链表

快慢指针

点击查看代码
public class Solution {
    public boolean hasCycle(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow){
                return true;
            }
        }
        return false;
    }
}
posted @ 2025-12-25 23:15  柳成荫y  阅读(0)  评论(0)    收藏  举报