LeetCode 203 & 237. Delete Node in a Linked List

时间:2022-06-13
本文章向大家介绍LeetCode 203 & 237. Delete Node in a Linked List,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

237.Delete Node in a Linked List

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

Given linked list -- head = [4,5,1,9], which looks like following:

    4 -> 5 -> 1 -> 9

Example 1:

Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5, the linked list
             should become 4 -> 1 -> 9 after calling your function.

Example 2:

Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: You are given the third node with value 1, the linked list
             should become 4 -> 5 -> 9 after calling your function.

解法:

public void deleteNode(ListNode node) {
  node.val = node.next.val;
  node.next=node.next.next;
}

这个题目比较简单,但是思路是不同于以往的,以往的思路总是想找到要删除的节点的前一个,删除节点,实际上在有一些情况,我们可以删除后一个,可以达到同样的目的。

203. Remove Linked List Elements

Remove all elements from a linked list of integers that have value val.

Example:

Input:  1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5

解法:

这是链表的最基础的题目,技巧就是采用一个虚拟头结点,可以方便的处理头结点的情况。

  public   ListNode removeElements(ListNode head, int val) {
                ListNode tempNode =new ListNode(0);
                tempNode.next = head;
                ListNode cur =tempNode ;
                while (cur.next != null){
                        if(cur.next.val == val){
                              cur.next = cur.next.next;
                        }else
                        cur = cur.next;
                }
                return tempNode.next;
        }

Remove Middle Node

解法:

涉及到对链表的正中间的节点的节点的处理,首先要想到用快慢指针的思路来解决,实际上,链表中用到快慢指针的地方有很多,例如判断链表是否有环等。

public ListNode removeMidNode(ListNode head) {
    if (head == null || head.next == null) return head;
    if (head.next.next == null ) return  head.next;
    ListNode dunny = new ListNode(0);
    dunny.next = head;
    ListNode slow = dunny;
    ListNode fast = head.next;
    while (fast != null && fast.next != null){
        slow = slow.next;
        fast = fast.next.next;
    }
    slow.next = slow.next.next;
    return head;
}