1.反转链表比较简单
思路一就是两个指针,一个记录前面的位置,一个记录后面的位置;
思路二是递归,到最后一个位置的时候(此时指针的位置在倒数第二个),
执行 head.next.next=head;head.next=null;
代码如下:
package com.codeking.lc;
/**
* @author xiongjl
* @since 2023/8/8 21:58
*/
public class lc206 {
public static void main(String[] args) {
ListNode2 listNode2 = new ListNode2(1);
listNode2.next = new ListNode2(2);
listNode2.next.next = new ListNode2(3);
new lc206().reverseList(listNode2);
}
public ListNode2 reverseList(ListNode2 head) {
ListNode2 pre = null;
ListNode2 cur = head;
ListNode2 next = null;
while (cur != null) {
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
/*public ListNode3 reverseList(ListNode3 head) {
if (head == null || head.next == null) {
return head;
}
ListNode3 temp = reverseList(head.next);
head.next.next = head;
head.next = null;
return temp;
}*/
/**
* 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 ListNode2 {
int val;
ListNode2 next;
ListNode2() {
}
ListNode2(int val) {
this.val = val;
}
ListNode2(int val, ListNode2 next) {
this.val = val;
this.next = next;
}
}
2. 回文链表
关键的思路是取到中间的位置,然后反转后面的链表,然后进行比较
package com.codeking.lc;
/**
* @author xiongjl
* @since 2023/8/9 21:55
*/
public class lc234 {
public static void main(String[] args) {
ListNode3 listNode3 = new ListNode3(1);
listNode3.next = new ListNode3(2);
lc234 lc234 = new lc234();
boolean palindrome = lc234.isPalindrome(listNode3);
System.out.println(palindrome);
}
public boolean isPalindrome(ListNode3 head) {
ListNode3 temp = head;
int len = 0;
while (temp != null) {
len++;
temp = temp.next;
}
int mid = len / 2;
temp = head;
for (int i = 0; i < mid; i++) {
temp = temp.next;
}
// 翻转链表
temp = reverseList(temp);
while (temp != null) {
if (head.val != temp.val) {
return false;
}
head = head.next;
temp = temp.next;
}
return true;
}
public ListNode3 reverseList(ListNode3 head) {
if (head == null || head.next == null) {
return head;
}
ListNode3 temp = reverseList(head.next);
head.next.next = head;
head.next = null;
return temp;
}
}
class ListNode3 {
int val;
ListNode3 next;
ListNode3() {
}
ListNode3(int val) {
this.val = val;
}
ListNode3(int val, ListNode3 next) {
this.val = val;
this.next = next;
}
}
3.环状链表
最关键是需要有一个快慢指针,快指针速度快一步。
package com.codeking.lc;
/**
* @author xiongjl
* @since 2023/8/9 22:31
*/
public class lc141 {
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
// 快慢指针
ListNode fast = head.next;
while (true) {
if (fast == null || fast.next == null) {
return false;
}
fast = fast.next.next;
head = head.next;
if (fast == head) {
return true;
}
}
}
}