1 删除链表中等于给定值 val 的所有节点.
先处理非头部节点, 最后处理头部节点.
class ListNode {
int val = 0;
ListNode next = null;
public ListNode(int val) {
this.val = val;
}
}
public class LinkedListTest {
public ListNode removeElements(ListNode head, int val) {
if (head == null) {
return null;
}
1. 先删除中间节点的情况(非头部的情况)
ListNode prev = head; // prev 始终指向 cur 的前一个位置
ListNode cur = head.next;
while (cur != null) {
if (cur.val == val) {
prev.next = cur.next;
cur = prev.next;
} else {
prev = cur;
cur = cur.next;
}
}
2. 最后再考虑删除头结点的情况(放到最后, 只需要处理一次即可)
if (head.val == val) {
head = head.next;
}
return head;
}
}
2 反转一个单链表.
定义三个节点, pre, next, 新的头结点. 最后返回的是 新的头结点.
public ListNode reverseList(ListNode head) {
if (head == null) {
return null;
}
if (head.next == null) {
return head;
}
ListNode newHead = null;
ListNode cur = head;
ListNode prev = null;
while (cur!=null){
ListNode next=cur.next;
if(next==null){
newHead=cur;
}
cur.next=prev;
prev=cur;
cur=next;
}
return newHead;
}
3 给定一个带有头结点 head 的非空单链表,返回链表的中间结点. 如果有两个中间结点,则返回第二个中间结点.
先求链表长度, 然后求要走的步数. 是 <steps, 不是 <=steps.
public ListNode middleNode(ListNode head) {
int steps = size(head) / 2;
ListNode cur = head