甘南藏族自治州网站建设_网站建设公司_Vue_seo优化
2025/12/25 23:20:47 网站建设 项目流程

相交链表

点击查看代码
/*** 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;}
}

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询