CCI 2.1 移除未排序連結串列中的重複節點
阿新 • • 發佈:2019-02-05
編寫程式碼,移除未排序連結串列中的重複節點。
進階,
如果不得使用臨時緩衝區,該怎麼解決?
package test; import java.util.HashSet; public class RemoveDup { //利用HashSet public Node removeDup(Node head){ if(head==null || head.next==null) return head; Node newHead = new Node(0); newHead.next = head; Node point = newHead; HashSet<Integer> set = new HashSet<Integer>(); while(point.next != null){ if(set.contains(point.next.val)) point.next = point.next.next; else{ set.add(point.next.val); point = point.next; } } return newHead.next; } //不利用臨時緩衝區 public Node removeDup(Node head){ if(head==null || head.next==null) return head; Node current = head; while(current != null){ Node point = current; whille(point.next != null){ if(point.next.val == current.val) point.next = point.next.next; else point = point.next; } current = current.next; } return head; } }