
操作:




先将头节点以外的删除再来考虑头节点位置即可 if(head.val == val) { head = head.next; }

也可先考虑头节点的情况,while循环判断

public void removeAllKey(int val) {
//1. 判空
if (head == null) {
head = head.next;
}
//2. 定义prev 和 cur
ListNode prev = head;
ListNode cur = head.next;
//3.开始判断并且删除
while (cur != null) {
if (cur.val == val) {
//找到了
prev.next = cur.next;
} else {
prev = cur;
}
cur = cur.next;
}
//4.处理头节点
if(head.val == val) {
head = head.next;
}
}public ListNode removeElements(ListNode head, int val) {
// 1. 处理头节点
while (head != null && head.val == val) {
head = head.next;
}
// 2. 如果链表为空,直接返回
if (head == null) {
return head;
}
ListNode cur = head;
// 3. 开始判断并且删除
while (cur.next != null) {
if (cur.next.val == val) {
// 找到了
ListNode del = cur.next;
cur.next = del.next;
} else {
cur = cur.next;
}
}
// 4. 这里不需要再处理头节点,因为在循环开始前已经处理过了
return head;
} https://leetcode.cn/problems/reverse-linked-list/description/

思路:

操作:
public ListNode reverseList(ListNode head) {
if (head == null) {
return head;
}
ListNode cur = head.next;
head.next = null;
while (cur != null) {
ListNode curN = cur.next;
cur.next = head;
head = cur;
cur = curN;
}
return head;
}https://leetcode.cn/problems/middle-of-the-linked-list/description/

(3)题解
寻找中间节点用到了非常经典的快慢指针方法 思路:
操作:

public ListNode middleNode(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while (fast != null && fast.next != null) {
ListNode tmp = fast.next;
fast = tmp.next;
slow = slow.next;
}
return slow;
}https://leetcode.cn/problems/kth-node-from-end-of-list-lcci/description/

思路: 因为题目要求是返回导数第k个节点,在这里我们依然使用的是快慢指针方法 我们先让fast走k步,来抵消倒数的这个差值,然后再让fast和slow同时走

操作:
public int kthToLast(ListNode head, int k) {
ListNode fast = head;
ListNode slow = head;
for(int i = 0;i < k;i++) {
fast = fast.next;
}
while(fast != null) {
fast = fast.next;
slow = slow.next;
}
return slow.val;
}https://leetcode.cn/problems/merge-two-sorted-lists/description/

思路:
操作:
public ListNode mergeTwoLists(ListNode headA, ListNode headB) {
ListNode newH = new ListNode();
ListNode tmp = newH;
while(headA != null && headB != null) {
if(headA.val < headB.val) {
tmp.next = headA;
headA = headA.next;
tmp = tmp.next;
} else{
tmp.next = headB;
headB = headB.next;
tmp = tmp.next;
}
}
if(headA != null) {
tmp.next = headA;
} else {
tmp.next = headB;
}
return newH.next;
}