鏈表問題----刪除鏈表的中間節點和a/b處的節點
阿新 • • 發佈:2018-07-15
color mil 節點 font import 進階 spa 復雜 code
刪除鏈表的中間節點和a/b處的節點
對於給定一個鏈表的頭節點head,實現刪除鏈表的中間節點的函數。
例如
不刪除任何節點;
1->2,刪除節點1
1->2->3,刪除節點2
1->2->3->4,刪除節點2
1->2->3->4->5,刪除節點3
如果將本問題復雜一下,給定鏈表的頭節點head、整數a和整數b,實現刪除位於a/b處節點的函數。
例如
鏈表:1->2->3->4->5,假設 a/b 的值為r
如果 r 等於0,不刪除任何節點
如果 r 在區間(0,1/5]上,刪除節點 1
如果 r 在區間(1/5,2/5]上,刪除節點 2
如果 r 在區間(2/5,3/5]上,刪除節點 3
如果 r 在區間(3/5,4/5]上,刪除節點 4
如果 r 在區間(4/5,1]上,刪除節點 5
如果 r 大於1,不刪除任何節點
package com.test; import com.tset.ListNode; /** * Created by Demrystv. */ public class RemoveListNode { // 針對普通問題,采用的方法是找規律,當元素個數大於3時,鏈表長度每增加2,要刪除的節點就要後移一個節點 publicListNode removeMiddle(ListNode head){ // 針對的是沒有元素或者只有一個元素 if (head == null || head.next == null){ return null; } // 針對的是只有兩個元素 if (head.next.next == null){ return head.next; } // 針對的是三個及三個以上元素,這時符合規律 ListNode pre = head; ListNode cur= head.next.next; while (pre.next != null && cur.next.next != null){ pre = pre.next; cur = cur.next.next; } pre.next = pre.next.next; return head; } // 針對進階問題,主要是找到n,即要刪除的元素的位置 public ListNode removeByRatio(ListNode head, int a ,int b){ if (a < 1 || a > b){ return head; } // 求鏈表的長度 int n = 0; ListNode cur = head; while (cur != null){ n++; cur = cur.next; } // n表示要刪除的節點是第幾個節點,可以舉例證明,也可以通過舉例來推導 n = (int) Math.ceil((double)(a * n) / (double) b); // 其原理類似於刪除倒數第K 個節點 if (n == 1){ return head.next; } if (n > 1){ cur = head; while (--n != 0){ cur = cur.next; } cur.next = cur.next.next; } return head; } }
鏈表問題----刪除鏈表的中間節點和a/b處的節點