[Linked List] 2095. Delete the intermediate node of the linked list

2095. Delete the middle node of the linked list

problem solving ideas

  • To delete the intermediate node of the linked list, first find the predecessor node
  • First count the length of the linked list and calculate n / 2 -1, which is the node before the middle node
  • Then traverse the linked list to find the predecessor node and delete it at last
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    
    
    public ListNode deleteMiddle(ListNode head) {
    
    
        // 首先计算链表的长度
        int count = 0;
        ListNode cur = head;
        while(cur != null){
    
    
            count++;
            cur = cur.next;
        }

        if(count == 1){
    
    
            return null;
        }

        if(count == 2){
    
    
            head.next = null;
            return head;
        }

        // 要删除中间节点  那么需要找到中间节点的前一个节点
        cur = head;
        int x = count / 2 - 1;
        while(x-- > 0){
    
    
            cur = cur.next;
        }

        // 删除中间节点
        cur.next = cur.next.next;
        return head;
    }
}

Guess you like

Origin blog.csdn.net/qq_44653420/article/details/131717829