zoukankan      html  css  js  c++  java
  • 【IT笔试面试题整理】删除无序链表中重复的节点

    【试题描述】定义一个函数,输入一个链表,删除无序链表中重复的节点

    【参考代码】

    方法一:

    Without a buffer, we can iterate with two pointers: “current” does a normal iteration, while 
    “runner” iterates through all prior nodes to check for dups Runner will only see one dup 
    per node, because if there were multiple duplicates they would have been removed already

     1 public static void deleteDups(LinkList head)
     2     {
     3         if (head == null)
     4             return;
     5         Link previous = head.first;
     6         Link current = previous.next;
     7         while (current != null)
     8         {
     9             Link runner = head.first;
    10             while (runner != current)
    11             {
    12                 if (runner.id == current.id)
    13                 {
    14                     Link tmp = current.next;
    15                     previous.next = tmp;
    16                     current = tmp;
    17                     break;
    18                 }
    19                 runner = runner.next;
    20             }
    21 
    22             if (runner == current)
    23             {
    24                 previous = current;
    25                 current = current.next;
    26             }
    27         }
    28 
    29         System.out.println("-----------");
    30         head.displayList();
    31     }


    方法二:

    If we can use a buffer, we can keep track of elements in a hashtable and remove any dups:

        public static void deleteDups2(LinkList head)
        {
            if (head == null)
                return;
            Hashtable table = new Hashtable();
            Link previous = null;
            Link current = head.first;
            while (current != null)
            {
                if (table.containsKey(current.id))
                    previous.next = current.next;
                else
                {
                    table.put(current.id, true);
                    previous = current;
                }
                current = current.next;
            }
            System.out.println("-----------");
            head.displayList();
        }
  • 相关阅读:
    Emacs for OIer 的一些配置
    CF1336E Chiori and Doll Picking 【线性代数,组合计数】
    CF605E Intergalaxy Trips 【贪心,动态规划,期望】
    Luogu6329 【模板】点分树 | 震波
    [SDOI2014]数表
    [BZOJ4403]序列统计
    [BZOJ5099]Pionek
    SP1812 LCS2
    SA & SAM
    [HAOI2016]找相同字符
  • 原文地址:https://www.cnblogs.com/WayneZeng/p/3015303.html
Copyright © 2011-2022 走看看