編碼實現從無序鏈表中移除重複項(C和JAVA執行個體)_java

來源:互聯網
上載者:User

如果不能使用臨時緩衝,你怎麼編碼實現?

複製代碼 代碼如下:

方法一:不使用額外的儲存空間,直接在原始鏈表上進行操作。首先用一個指標指向鏈表前端節點開始,然後遍曆其後面的節點,將與該指標所指節點資料相同的節點刪除。然後將該指標後移一位,繼續上述操作。直到該指標移到鏈表。

void delete_duplicate1(node* head){
    node*pPos=head->next;
    node*p,*q;
    while(pPos!=NULL){//用pPos指標來指示當前移動到什麼位置了
        p=pPos;
       q=pPos->next;
       while(q!=NULL){//遍曆pPos後面的所有節點,找出節點值與pPos所指節點相同的節點,將其刪除
            if(pPos->data==q->data){
                node*pDel=q;
                p->next=q->next;
                q=p->next;
                free(pDel);
                }
            else{
                p=q;
                q=q->next;
                }
            }
        pPos=pPos->next;
        }
}


方法二:如果允許使用額外的空間,則能通過空間換時間,來降低演算法的複製度。可以使用hash表來完成,既然是面試題,我們這裡可以暫時先不考慮使用hash可能帶來的一些問題,先假設它是完美的。即假設它能將任意整數hash到一定範圍,不會出現負數下標,不會出現hash衝突等。
複製代碼 代碼如下:

void delete_duplicate2(node* head)
{
    node*p=head->next;
    node*q=p->next;
    memset(hash,0,sizeof(hash));
    hash[p->data]=1;//置為1,表示該數已經出現過
    while(q!=NULL){
        if(hash[q->data]!=0){
            node*pDel=q;
            p->next=q->next;
            q=p->next;
            free(pDel);
            }
        else{
            hash[q->data]=1;//置為1,表示該數已經出現過
            p=q;
            q=q->next;
            }
        }
}

JAVA參考代碼:

複製代碼 代碼如下:

public static void deleteDups(LinkedListNode n) {
  Hashtable table = new Hashtable();
  LinkedListNode previous = null;
  while (n != null) {
    if (table.containsKey(n.data)) previous.next = n.next;
    else {
      table.put(n.data, true);
      previous = n;
    }
    n = n.next;
  }
}
public static void deleteDups2(LinkedListNode head) {
    if (head == null) return;
    LinkedListNode previous = head;
    LinkedListNode current = previous.next;
    while (current != null) {
      LinkedListNode runner = head;
      while (runner != current) { // Check for earlier dups
        if (runner.data == current.data) {
          LinkedListNode tmp = current.next; // remove current
          previous.next = tmp;
          current = tmp; // update current to next node
          break; // all other dups have already been removed
        }
        runner = runner.next;
      }
      if (runner == current) { // current not updated - update now
        previous = current;
        current = current.next;
      }
    }
 }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.