题目来自《代码随想录》
203.移除链表元素
https://leetcode-cn.com/problems/remove-linked-list-elements/
public ListNode removeElements(ListNode head, int val) {
if(head == null) return head;
ListNode dummy = new ListNode(0, head);
ListNode pre = dummy;
ListNode cur = head;
while(cur != null){
//System.out.println("nex.val=" + cur.val);
if(cur.val == val){
//System.out.println("进");
pre.next = cur.next;
}else{
pre = cur;
}
cur = cur.next;
}
return dummy.next;
}
206. 反转链表
https://leetcode-cn.com/problems/reverse-linked-list/
public ListNode reverseList(ListNode head) {
if(head == null) return head;
ListNode pre = null;
ListNode cur = head;
ListNode temp = null; //存储每次的下一个
while(cur != null){
temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
24. 两两交换链表中的节点
https://leetcode-cn.com/problems/swap-nodes-in-pairs/
public ListNode swapPairs(ListNode head) {
if(head == null) return head;
ListNode dummy = new ListNode(0, head);
ListNode pre = dummy;
while(pre.next != null && pre.next.next != null){
ListNode temp = head.next.next;
pre.next = head.next;
head.next.next = head;
head.next = temp;
pre = head;
head = pre.next;
}
return dummy.next;
}
19. 删除链表的倒数第 N 个结点
https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode slow = dummy;
ListNode fast = dummy;
while (n-- > 0) {
fast = fast.next;
}
// 记住 待删除节点slow 的上一节点
ListNode prev = null;
while (fast != null) {
prev = slow;
slow = slow.next;
fast = fast.next;
}
// 上一节点的next指针绕过 待删除节点slow 直接指向slow的下一节点
prev.next = slow.next;
// 释放 待删除节点slow 的next指针, 这句删掉也能AC
slow.next = null;
return dummy.next;
}
面试题 02.07. 链表相交
https://leetcode-cn.com/problems/intersection-of-two-linked-lists-lcci/
- 注意curA和B是定义成head还是他们的next是head
public ListNode getIntersectionNode1(ListNode headA, ListNode headB) {
ListNode curA = headA;
ListNode curB = headB;
int lenA = 0, lenB = 0;
while (curA != null) { // 求链表A的长度
lenA++;
curA = curA.next;
}
while (curB != null) { // 求链表B的长度
lenB++;
curB = curB.next;
}
curA = headA;
curB = headB;
// 让curA为最长链表的头,lenA为其长度
if (lenB > lenA) {
//1. swap (lenA, lenB);
int tmpLen = lenA;
lenA = lenB;
lenB = tmpLen;
//2. swap (curA, curB);
ListNode tmpNode = curA;
curA = curB;
curB = tmpNode;
}
// 求长度差
int gap = lenA - lenB;
// 让curA和curB在同一起点上(末尾位置对齐)
while (gap-- > 0) {
curA = curA.next;
}
// 遍历curA 和 curB,遇到相同则直接返回
while (curA != null) {
if (curA == curB) {
return curA;
}
curA = curA.next;
curB = curB.next;
}
return null;
}
142. 环形链表 II
https://leetcode-cn.com/problems/linked-list-cycle-ii/
注意:while的判断条件
public ListNode detectCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){ //存在环
ListNode in1 = fast;
ListNode in2 = head;
while(in1 != in2) {
in1 = in1.next;
in2 = in2.next;
}
return in1;
}
}
return null;
}