1. 链表的回文结构
思路:
经过以前做题的经验,要找回文结构,我们首先要找他的中心结点,--->中心节点的求法,我们在上次已经写过了,那就直接用。找到了中心结点,那我们要做的是,将前半段反转,上次也写过了。(链表的练习题_大干部的博客-CSDN博客),最终我们要写的只是,让两边的结点同时走,比较其的val,就可以了。
代码:
public class PalindromeList {
public boolean chkPalindrome(ListNode A) {
// write code here
//1、找到链表的中间节点
if (A == null) {
return true;
}
if (A.next == null) {
return true;
}
ListNode fast = A;
ListNode slow = A;
while (fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
//2、翻转
ListNode cur = slow.next;
while (cur != null) {
ListNode curNext = cur.next;
cur.next = slow;
slow = cur;
cur = curNext;
}
//3、开始一个从头走,一个从尾巴走,直到相遇
while (A != slow) {
if (A.val != slow.val) {
return false;
}
if (A.next == slow){
return true;
}
A = A.next;
slow = slow.next;
}
return true;
}
2. 输入两个链表,找出它们的第一个公共结点。
思路:
代码:
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA == null || headB == null) {
return null;
}
ListNode pl = headA;//指向长的链表
ListNode ps = headB;//指向短的链表
//1、分别求长度
int lenA = 0;
int lenB = 0;
while (pl != null) {
lenA++;
pl = pl.next;
}
while (ps != null) {
lenB++;
ps = ps.next;
}
//需要重新修改指向
pl = headA;
ps = headB;
//2、已经知道两个链表的长度了
int len = lenA-lenB;
if(len < 0) {
pl = headB;
ps = headA;
len = lenB - lenA;
}
//1、求长度 2、pl永远指向 最长的那个链表 ps永远指向最短的那个链表
//3、就是让最长的链表走len步
while (len != 0){
pl = pl.next;
len--;
}
//4、一人一步走 直到相遇
while (pl != ps) {
pl = pl.next;
ps = ps.next;
}
//5、是不是两个都是null-》没有相交
/*if (pl == null){
return null;
}*/
return pl;
}
}
9. 给定一个链表,判断链表中是否有环
思路:
就和追赶问题一样,定义两个指针,一个每次.next.next,另一个每次.next,如果有环,那他两一定会相遇。
代码:
/**
* 给定一个链表,判断链表中是否有环。
* 判断链表是否有环
* @param head
* @return
*/
public boolean hasCycle(ListNode head) {
if (head == null) {
return false;
}
if (head.next == null) {
return false;
}
ListNode fast = head;
ListNode slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
return true;
}
}
return false;
}