1. 程式人生 >實用技巧 >其它 >刪除連結串列的中間節點和 a/b 處的節點

刪除連結串列的中間節點和 a/b 處的節點


刪除連結串列的中間節點和 a/b 處的節點

首先是刪除中間節點

連結串列長度為n,

n = 0, 不刪除;

n = 1, 不刪除;

n = 2, 刪除第 1 個節點;

n = 3, 刪除第 2 個節點;

n = 4, 刪除第 2個節點;

n = 5, 刪除第 3 個節點;

n = 6, 刪除第 3 個節點;

n = 7, 刪除第 4 個節點;

總結:從連結串列長度大於等於2時,每增加兩個節點,刪除節點後移一位。

具體程式碼

public static Node removeMidNode(Node head) {
    if (head == null || head.next == null) {
        return head;
    }
    if (head.next.next == null) {
        return head.next;
    }
    Node pre = head;
    Node cur = head.next.next;
    while (cur.next != null && cur.next.next != null) {
        pre = pre.next;
        cur = cur.next.next;
    }
    pre.next = pre.next.next;
    return head;
}
public static void print(Node head) {
    while (head != null) {
        System.out.print(head.value + " ");
        head = head.next;
    }
}
public static void main(String[] args) {
    Node head1 = new Node(1);
    head1.next = new Node(3);
    head1.next.next = new Node(5);
    head1.next.next.next = new Node(6);
    head1.next.next.next.next = new Node(7);
    head1.next.next.next.next.next = new Node(3);
    print(removeMidNode(head1));
}

輸出結果

刪除連結串列的中間節點和 a/b 處的節點

刪除 a/b 處的節點

比如:a=2 b=5 n=6,那麼刪除2/5處的節點就是(2/5)*6=2.4處的節點,凡是出現小數則向上取整,則刪除的是第三個節點。

具體程式碼

public static Node removeByRatio(Node head, int a, int b) {
    if (a > b || head == null) {
        return head;
    }
    int n = 0;
    Node cur = head;
    //算出連結串列的長度
    while (cur != null) {
        n++;
        cur = cur.next;
    }
    n = (int) Math.ceil(((double) (a*n))/((double)b));
    if(n==1){
        head = head.next;
    }
    if(n>1){
        cur = head;
        while (--n!=1){
            cur = cur.next;
        }
        cur.next = cur.next.next;
    }
    return head;
}
public static void main(String[] args) {
    Node head1 = new Node(1);
    head1.next = new Node(3);
    head1.next.next = new Node(5);
    head1.next.next.next = new Node(6);
    head1.next.next.next.next = new Node(7);
    head1.next.next.next.next.next = new Node(3);
    print(removeByRatio(head1,3,5));
}

輸出結果

刪除連結串列的中間節點和 a/b 處的節點