链表习题一定要画图!
例一 :链表的回文结构
题目详述:
对于一个链表,请设计一个时间复杂度为O(n),额外空间复杂度为O(1)的算法,判断其是否为回文结构。
例:1->2->2->1
返回:true
public class PalindromeList {
public boolean chkPalindrome(ListNode A) {
ListNode fast = A;
ListNode slow = A;
while(fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
ListNode nextMid = slow.next;
//逆置
while(nextMid != null){
ListNode next = nextMid.next;
nextMid.next = slow;
slow = nextMid;
nextMid = next;
}
while(slow != A) {
if(slow.val != A.val) {
return false;
}
if(A.next == slow) {
return true;
}
A = A.next;
slow = slow.next;
}
return true;
}
}
例二 :给定一个链表,判断链表中是否有环
题目详述:
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
示例一:
示例二:
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
boolean hasCycle = false;
while(fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if(fast == slow) {
return true;
}
}
return false;
}
}
例三 :给定一个链表,返回链表开始入环的第一个节点
说明:不允许修改给定的链表
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 cur = head;
while(slow != cur) {
slow = slow.next;
cur = cur.next;
}
return slow;
}
}
return null;
}
}
例四 :奇偶链表
题目详述:
给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。
PS:这里的奇数节点和偶数节点指的是节点编号的奇偶性,而不是节点的值的奇偶性。
class Solution {
public ListNode oddEvenList(ListNode head) {
if(head == null || head.next == null) {
return head;
}
//head 为奇链表头节点, tail 为奇链表尾节点
ListNode tail = head;
//h 为偶链表头节点, t 为偶链表尾结点
ListNode h = head.next;
ListNode t = h;
while(tail.next != null && t.next != null) {
tail.next = t.next;
tail = tail.next;
t.next = tail.next;
t = t.next;
}
tail.next = h;
return head;
}
}
例五 :移除链表元素
题目详述:
删除链表中等于给定值 val 的所有节点
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode node = new ListNode(-1);
ListNode cur = node;
cur.next = head;
while(cur.next != null ) {
if(cur.next.val == val) {
cur.next = cur.next.next;
}else {
cur = cur.next;
}
}
return node.next;
}
}