zoukankan      html  css  js  c++  java
  • (转)面试大总结之一:Java搞定面试中的链表题目

    面试大总结之一:Java搞定面试中的链表题目

    分类: Algorithm Interview 11628人阅读 评论(40) 收藏 举报

    链表是面试中常出现的一类题目,本文用Java实现了面试中常见的链表相关题目。本文主要参考整合重写了《轻松搞定面试中的链表题目》和 《算法大全(1)单链表》两篇大作。两篇大神的实现分别是C和C#,因为我更喜欢用Java面试,所以用Java重写了所有实现,并附上自己的一些思考注释。算法大全(1)单链表 尚未有一些问题尚未整合进来,很快我会更新本文。接下来还会出关于二叉树的总结和栈和队列的大总结。因为这些都属于面试中的送分题!必须毫无偏差地拿下。至于像动态规划这些比较“高端”的算法,就只能靠日积月累,而不能像这样临时突击了。


    第二篇: 《面试大总结之二:Java搞定面试中的二叉树题目》已经出炉!



     

    [java] view plaincopy
     
    1. package LinkedListSummary;  
    2.   
    3. import java.util.HashMap;  
    4. import java.util.Stack;  
    5.   
    6. /** 
    7.  * http://blog.csdn.net/luckyxiaoqiang/article/details/7393134 轻松搞定面试中的链表题目 
    8.  * http://www.cnblogs.com/jax/archive/2009/12/11/1621504.html 算法大全(1)单链表 
    9.  *  
    10.  * 目录: 
    11.  * 1. 求单链表中结点的个数: getListLength 
    12.  * 2. 将单链表反转: reverseList(遍历),reverseListRec(递归) 
    13.  * 3. 查找单链表中的倒数第K个结点(k > 0): reGetKthNode 
    14.  * 4. 查找单链表的中间结点: getMiddleNode 
    15.  * 5. 从尾到头打印单链表: reversePrintListStack,reversePrintListRec(递归) 
    16.  * 6. 已知两个单链表pHead1 和pHead2 各自有序,把它们合并成一个链表依然有序: mergeSortedList, mergeSortedListRec 
    17.  * 7. 判断一个单链表中是否有环: hasCycle 
    18.  * 8. 判断两个单链表是否相交: isIntersect 
    19.  * 9. 求两个单链表相交的第一个节点: getFirstCommonNode 
    20.  * 10. 已知一个单链表中存在环,求进入环中的第一个节点: getFirstNodeInCycle, getFirstNodeInCycleHashMap 
    21.  * 11. 给出一单链表头指针pHead和一节点指针pToBeDeleted,O(1)时间复杂度删除节点pToBeDeleted: delete 
    22.  *  
    23.  */  
    24. public class Demo {  
    25.   
    26.     public static void main(String[] args) {  
    27.         Node n1 = new Node(1);  
    28.         Node n2 = new Node(2);  
    29.         Node n3 = new Node(3);  
    30.         Node n4 = new Node(4);  
    31.         Node n5 = new Node(5);  
    32.         n1.next = n2;  
    33.         n2.next = n3;  
    34.         n3.next = n4;  
    35.         n4.next = n5;  
    36.   
    37.         printList(n1);  
    38. //      System.out.println(getListLength(n1));  
    39. //      Node head = reverseList(n1);  
    40. //      Node head = reverseListRec(n1);  
    41. //      printList(head);  
    42.   
    43.         Node x = reGetKthNode(n1, 2);  
    44.         System.out.println(x.val);  
    45.         reGetKthNodeRec(n1, 2);  
    46.           
    47.           
    48. //      x = getMiddleNode(head);  
    49. //      System.out.println(x.val);  
    50. //      System.out.println("reversePrintListStack:");  
    51. //      reversePrintListStack(head);  
    52. //      System.out.println("reversePrintListRec:");  
    53. //      reversePrintListRec(head);  
    54.   
    55.     }  
    56.   
    57.       
    58. //  public static void main(String[] args) {  
    59. //      Node n1 = new Node(1);  
    60. //      Node n2 = new Node(3);  
    61. //      Node n3 = new Node(5);  
    62. //      n1.next = n2;  
    63. //      n2.next = n3;  
    64. //  
    65. //      Node m1 = new Node(1);  
    66. //      Node m2 = new Node(4);  
    67. //      Node m3 = new Node(6);  
    68. //      m1.next = m2;  
    69. //      m2.next = m3;  
    70. //        
    71. //        
    72. //      Node ret = mergeSortedList(n1, m1);  
    73. //      printList(ret);  
    74. //  }  
    75.   
    76.     private static class Node {  
    77.         int val;  
    78.         Node next;  
    79.   
    80.         public Node(int val) {  
    81.             this.val = val;  
    82.         }  
    83.     }  
    84.   
    85.     public static void printList(Node head) {  
    86.         while (head != null) {  
    87.             System.out.print(head.val + " ");  
    88.             head = head.next;  
    89.         }  
    90.         System.out.println();  
    91.     }  
    92.   
    93.     // 求单链表中结点的个数  
    94.     // 注意检查链表是否为空。时间复杂度为O(n)  
    95.     public static int getListLength(Node head) {  
    96.         // 注意头结点为空情况  
    97.         if (head == null) {  
    98.             return 0;  
    99.         }  
    100.   
    101.         int len = 0;  
    102.         Node cur = head;  
    103.         while (cur != null) {  
    104.             len++;  
    105.             cur = cur.next;  
    106.         }  
    107.         return len;  
    108.     }  
    109.   
    110.     // 翻转链表(遍历)  
    111.     // 从头到尾遍历原链表,每遍历一个结点,  
    112.     // 将其摘下放在新链表的最前端。  
    113.     // 注意链表为空和只有一个结点的情况。时间复杂度为O(n)  
    114.     public static Node reverseList(Node head) {  
    115.         // 如果链表为空或只有一个节点,无需反转,直接返回原链表表头  
    116.         if (head == null || head.next == null) {  
    117.             return head;  
    118.         }  
    119.   
    120.         Node reHead = null;         // 反转后新链表指针  
    121.         Node cur = head;  
    122.   
    123.         while (cur != null) {  
    124.             Node preCur = cur;      // 用preCur保存住对要处理节点的引用  
    125.             cur = cur.next;             // cur更新到下一个节点  
    126.             preCur.next = reHead;   // 更新要处理节点的next引用  
    127.             reHead = preCur;            // reHead指向要处理节点的前一个节点  
    128.         }  
    129.   
    130.         return reHead;  
    131.     }  
    132.       
    133.     // 翻转递归(递归)  
    134.     // 递归的精髓在于你就默认reverseListRec已经成功帮你解决了子问题了!但别去想如何解决的  
    135.     // 现在只要处理当前node和子问题之间的关系。最后就能圆满解决整个问题。  
    136.     /* 
    137.          head 
    138.             1 -> 2 -> 3 -> 4 
    139.          
    140.           head 
    141.             1-------------- 
    142.                                 | 
    143.                    4 -> 3 -> 2                            // Node reHead = reverseListRec(head.next); 
    144.                reHead      head.next 
    145.              
    146.                    4 -> 3 -> 2 -> 1                    // head.next.next = head; 
    147.                reHead 
    148.                 
    149.                     4 -> 3 -> 2 -> 1 -> null            // head.next = null; 
    150.                reHead 
    151.      */  
    152.     public static Node reverseListRec(Node head){  
    153.         if(head == null || head.next == null){  
    154.             return head;  
    155.         }  
    156.           
    157.         Node reHead = reverseListRec(head.next);      
    158.         head.next.next = head;      // 把head接在reHead串的最后一个后面  
    159.         head.next = null;               // 防止循环链表  
    160.         return reHead;  
    161.     }  
    162.   
    163.     /** 
    164.      * 查找单链表中的倒数第K个结点(k > 0) 
    165.      * 最普遍的方法是,先统计单链表中结点的个数,然后再找到第(n-k)个结点。注意链表为空,k为0,k为1,k大于链表中节点个数时的情况 
    166.      * 。时间复杂度为O(n)。代码略。 这里主要讲一下另一个思路,这种思路在其他题目中也会有应用。 
    167.      * 主要思路就是使用两个指针,先让前面的指针走到正向第k个结点 
    168.      * ,这样前后两个指针的距离差是k-1,之后前后两个指针一起向前走,前面的指针走到最后一个结点时,后面指针所指结点就是倒数第k个结点 
    169.      */  
    170.     public static Node reGetKthNode(Node head, int k) {  
    171.         // 这里k的计数是从1开始,若k为0或链表为空返回null  
    172.         if (k == 0 || head == null) {  
    173.             return null;  
    174.         }  
    175.   
    176.         Node q = head; // q在p前面  p--q  
    177.         Node p = head; // p在q后面  
    178.   
    179.         // 让q领先p距离k  
    180.         while (k > 1 && q != null) {  
    181.             q = q.next;  
    182.             k--;  
    183.         }  
    184.   
    185.         // 当节点数小于k,返回null  
    186.         if (k > 1 || q == null) {  
    187.             return null;  
    188.         }  
    189.   
    190.         // 前后两个指针一起走,直到前面的指针指向最后一个节点  
    191.         while (q.next != null) {  
    192.             p = p.next;  
    193.             q = q.next;  
    194.         }  
    195.   
    196.         // 当前面的指针指向最后一个节点时,后面的指针指向倒数k个节点  
    197.         return p;  
    198.     }  
    199.       
    200.       
    201.       
    202.     /** 
    203.      * 递归打印出倒数第k位的值 
    204.      * @param head 
    205.      * @param dist 
    206.      */  
    207.     static int level = 0;  
    208.     public static void reGetKthNodeRec(Node head, int k) {  
    209.           
    210.         if(head == null){  
    211.             return;  
    212.         }  
    213.         if(k == 1){  
    214.             return;  
    215.         }  
    216.           
    217.         reGetKthNodeRec(head.next, k);  
    218.         level++;  
    219.         if(level == k) {  
    220.             System.out.println(head.val);  
    221.         }  
    222.     }  
    223.       
    224.       
    225.       
    226.   
    227.     // 查找单链表的中间结点  
    228.     /** 
    229.      * 此题可应用于上一题类似的思想。也是设置两个指针,只不过这里是,两个指针同时向前走,前面的指针每次走两步,后面的指针每次走一步, 
    230.      * 前面的指针走到最后一个结点时,后面的指针所指结点就是中间结点,即第(n/2+1)个结点。注意链表为空,链表结点个数为1和2的情况。时间复杂度O(n 
    231.      */  
    232.     public static Node getMiddleNode(Node head) {  
    233.         if (head == null || head.next == null) {  
    234.             return head;  
    235.         }  
    236.   
    237.         Node q = head;      // p---q   
    238.         Node p = head;  
    239.   
    240.         // 前面指针每次走两步,直到指向最后一个结点,后面指针每次走一步  
    241.         while (q.next != null) {  
    242.             q = q.next;  
    243.             p = p.next;  
    244.             if (q.next != null) {  
    245.                 q = q.next;  
    246.             }  
    247.         }  
    248.         return p;  
    249.     }  
    250.   
    251.     /** 
    252.      * 从尾到头打印单链表 
    253.      * 对于这种颠倒顺序的问题,我们应该就会想到栈,后进先出。所以,这一题要么自己使用栈,要么让系统使用栈,也就是递归。注意链表为空的情况 
    254.      * 。时间复杂度为O(n) 
    255.      */  
    256.     public static void reversePrintListStack(Node head) {  
    257.         Stack<Node> s = new Stack<Node>();  
    258.         Node cur = head;  
    259.         while (cur != null) {  
    260.             s.push(cur);  
    261.             cur = cur.next;  
    262.         }  
    263.   
    264.         while (!s.empty()) {  
    265.             cur = s.pop();  
    266.             System.out.print(cur.val + " ");  
    267.         }  
    268.         System.out.println();  
    269.     }  
    270.   
    271.     /** 
    272.      * 从尾到头打印链表,使用递归(优雅!) 
    273.      */  
    274.     public static void reversePrintListRec(Node head) {  
    275.         if (head == null) {  
    276.             return;  
    277.         } else {  
    278.             reversePrintListRec(head.next);  
    279.             System.out.print(head.val + " ");  
    280.         }  
    281.     }  
    282.   
    283.     /** 
    284.      * 已知两个单链表pHead1 和pHead2 各自有序,把它们合并成一个链表依然有序 
    285.      * 这个类似归并排序。尤其注意两个链表都为空,和其中一个为空时的情况。只需要O(1)的空间。时间复杂度为O(max(len1, len2)) 
    286.      */  
    287.     public static Node mergeSortedList(Node head1, Node head2) {  
    288.         // 其中一个链表为空的情况,直接返回另一个链表头,O(1)  
    289.         if (head1 == null) {  
    290.             return head2;  
    291.         }  
    292.         if (head2 == null) {  
    293.             return head1;  
    294.         }  
    295.   
    296.         Node mergeHead = null;  
    297.         // 先确定下来mergeHead是在哪里  
    298.         if (head1.val < head2.val) {  
    299.             mergeHead = head1;  
    300.             head1 = head1.next;         // 跳过已经合并了的元素  
    301.             mergeHead.next = null;  // 断开mergeHead和后面的联系  
    302.         } else {  
    303.             mergeHead = head2;  
    304.             head2 = head2.next;  
    305.             mergeHead.next = null;  
    306.         }  
    307.   
    308.         Node mergeCur = mergeHead;  
    309.         while (head1 != null && head2 != null) {  
    310.             if (head1.val < head2.val) {  
    311.                 mergeCur.next = head1;       // 把找到较小的元素合并到merge中  
    312.                 head1 = head1.next;              // 跳过已经合并了的元素  
    313.                 mergeCur = mergeCur.next;    // 找到下一个准备合并的元素  
    314.                 mergeCur.next = null;            // 断开mergeCur和后面的联系  
    315.             } else {  
    316.                 mergeCur.next = head2;  
    317.                 head2 = head2.next;  
    318.                 mergeCur = mergeCur.next;  
    319.                 mergeCur.next = null;  
    320.             }  
    321.         }  
    322.   
    323.         // 合并剩余的元素  
    324.         if (head1 != null) {  
    325.             mergeCur.next = head1;  
    326.         } else if (head2 != null) {  
    327.             mergeCur.next = head2;  
    328.         }  
    329.   
    330.         return mergeHead;  
    331.     }  
    332.   
    333.     /** 
    334.      * 递归合并两链表(优雅!) 
    335.      */  
    336.     public static Node mergeSortedListRec(Node head1, Node head2) {  
    337.         if (head1 == null) {  
    338.             return head2;  
    339.         }  
    340.         if (head2 == null) {  
    341.             return head1;  
    342.         }  
    343.   
    344.         Node mergeHead = null;  
    345.         if (head1.val < head2.val) {  
    346.             mergeHead = head1;  
    347.             // 连接已解决的子问题  
    348.             mergeHead.next = mergeSortedListRec(head1.next, head2);  
    349.         } else {  
    350.             mergeHead = head2;  
    351.             mergeHead.next = mergeSortedListRec(head1, head2.next);  
    352.         }  
    353.         return mergeHead;  
    354.     }  
    355.   
    356.     /** 
    357.      * 判断一个单链表中是否有环 
    358.      * 这里也是用到两个指针。如果一个链表中有环,也就是说用一个指针去遍历,是永远走不到头的。因此,我们可以用两个指针去遍历,一个指针一次走两步 
    359.      * ,一个指针一次走一步,如果有环,两个指针肯定会在环中相遇。时间复杂度为O(n) 
    360.      */  
    361.     public static boolean hasCycle(Node head) {  
    362.         Node fast = head; // 快指针每次前进两步  
    363.         Node slow = head; // 慢指针每次前进一步  
    364.   
    365.         while (fast != null && fast.next != null) {  
    366.             fast = fast.next.next;  
    367.             slow = slow.next;  
    368.             if (fast == slow) { // 相遇,存在环  
    369.                 return true;  
    370.             }  
    371.         }  
    372.         return false;  
    373.     }  
    374.   
    375.     // 判断两个单链表是否相交  
    376.     /** 
    377.      * 如果两个链表相交于某一节点,那么在这个相交节点之后的所有节点都是两个链表所共有的。 也就是说,如果两个链表相交,那么最后一个节点肯定是共有的。 
    378.      * 先遍历第一个链表,记住最后一个节点,然后遍历第二个链表, 到最后一个节点时和第一个链表的最后一个节点做比较,如果相同,则相交, 
    379.      * 否则不相交。时间复杂度为O(len1+len2),因为只需要一个额外指针保存最后一个节点地址, 空间复杂度为O(1) 
    380.      */  
    381.     public static boolean isIntersect(Node head1, Node head2) {  
    382.         if (head1 == null || head2 == null) {  
    383.             return false;  
    384.         }  
    385.   
    386.         Node tail1 = head1;  
    387.         // 找到链表1的最后一个节点  
    388.         while (tail1.next != null) {  
    389.             tail1 = tail1.next;  
    390.         }  
    391.   
    392.         Node tail2 = head2;  
    393.         // 找到链表2的最后一个节点  
    394.         while (tail2.next != null) {  
    395.             tail2 = tail2.next;  
    396.         }  
    397.   
    398.         return tail1 == tail2;  
    399.     }  
    400.   
    401.     /** 
    402.      * 求两个单链表相交的第一个节点 对第一个链表遍历,计算长度len1,同时保存最后一个节点的地址。 
    403.      * 对第二个链表遍历,计算长度len2,同时检查最后一个节点是否和第一个链表的最后一个节点相同,若不相同,不相交,结束。 
    404.      * 两个链表均从头节点开始,假设len1大于len2 
    405.      * ,那么将第一个链表先遍历len1-len2个节点,此时两个链表当前节点到第一个相交节点的距离就相等了,然后一起向后遍历,直到两个节点的地址相同。 
    406.      * 时间复杂度,O(len1+len2) 
    407.      *  
    408.      *              ----    len2 
    409.      *                   |__________ 
    410.      *                   | 
    411.      *       ---------   len1 
    412.      *       |---|<- len1-len2 
    413.      */  
    414.     public static Node getFirstCommonNode(Node head1, Node head2) {  
    415.         if (head1 == null || head2 == null) {  
    416.             return null;  
    417.         }  
    418.         int len1 = 1;  
    419.         Node tail1 = head1;  
    420.         while (tail1.next != null) {  
    421.             tail1 = tail1.next;  
    422.             len1++;  
    423.         }  
    424.   
    425.         int len2 = 1;  
    426.         Node tail2 = head2;  
    427.         while (tail2.next != null) {  
    428.             tail2 = tail2.next;  
    429.             len2++;  
    430.         }  
    431.   
    432.         // 不相交直接返回NULL  
    433.         if (tail1 != tail2) {  
    434.             return null;  
    435.         }  
    436.   
    437.         Node n1 = head1;  
    438.         Node n2 = head2;  
    439.   
    440.         // 略过较长链表多余的部分  
    441.         if (len1 > len2) {  
    442.             int k = len1 - len2;  
    443.             while (k != 0) {  
    444.                 n1 = n1.next;  
    445.                 k--;  
    446.             }  
    447.         } else {  
    448.             int k = len2 - len1;  
    449.             while (k != 0) {  
    450.                 n2 = n2.next;  
    451.                 k--;  
    452.             }  
    453.         }  
    454.   
    455.         // 一起向后遍历,直到找到交点  
    456.         while (n1 != n2) {  
    457.             n1 = n1.next;  
    458.             n2 = n2.next;  
    459.         }  
    460.   
    461.         return n1;  
    462.     }  
    463.   
    464.     /** 
    465.      * 求进入环中的第一个节点 用快慢指针做(本题用了Crack the Coding Interview的解法,因为更简洁易懂!) 
    466.      */  
    467.     public static Node getFirstNodeInCycle(Node head) {  
    468.         Node slow = head;  
    469.         Node fast = head;  
    470.   
    471.         // 1) 找到快慢指针相遇点  
    472.         while (fast != null && fast.next != null) {  
    473.             slow = slow.next;  
    474.             fast = fast.next.next;  
    475.             if (slow == fast) { // Collision  
    476.                 break;  
    477.             }  
    478.         }  
    479.   
    480.         // 错误检查,这是没有环的情况  
    481.         if (fast == null || fast.next == null) {  
    482.             return null;  
    483.         }  
    484.   
    485.         // 2)现在,相遇点离环的开始处的距离等于链表头到环开始处的距离,  
    486.         // 这样,我们把慢指针放在链表头,快指针保持在相遇点,然后  
    487.         // 同速度前进,再次相遇点就是环的开始处!  
    488.         slow = head;  
    489.         while (slow != fast) {  
    490.             slow = slow.next;  
    491.             fast = fast.next;  
    492.         }  
    493.   
    494.         // 再次相遇点就是环的开始处  
    495.         return fast;  
    496.     }  
    497.   
    498.     /** 
    499.      * 求进入环中的第一个节点 用HashMap做 一个无环的链表,它每个结点的地址都是不一样的。 
    500.      * 但如果有环,指针沿着链表移动,那这个指针最终会指向一个已经出现过的地址 以地址为哈希表的键值,每出现一个地址,就将该键值对应的实值置为true。 
    501.      * 那么当某个键值对应的实值已经为true时,说明这个地址之前已经出现过了, 直接返回它就OK了 
    502.      */  
    503.     public static Node getFirstNodeInCycleHashMap(Node head) {  
    504.         HashMap<Node, Boolean> map = new HashMap<Node, Boolean>();  
    505.         while (head != null) {  
    506.             if (map.get(head) == true) {  
    507.                 return head; // 这个地址之前已经出现过了,就是环的开始处  
    508.             } else {  
    509.                 map.put(head, true);  
    510.                 head = head.next;  
    511.             }  
    512.         }  
    513.         return head;  
    514.     }  
    515.   
    516.     /** 
    517.      * 给出一单链表头指针head和一节点指针toBeDeleted,O(1)时间复杂度删除节点tBeDeleted 
    518.      * 对于删除节点,我们普通的思路就是让该节点的前一个节点指向该节点的下一个节点 
    519.      * ,这种情况需要遍历找到该节点的前一个节点,时间复杂度为O(n)。对于链表, 
    520.      * 链表中的每个节点结构都是一样的,所以我们可以把该节点的下一个节点的数据复制到该节点 
    521.      * ,然后删除下一个节点即可。要注意最后一个节点的情况,这个时候只能用常见的方法来操作,先找到前一个节点,但总体的平均时间复杂度还是O(1) 
    522.      */  
    523.     public void delete(Node head, Node toDelete){  
    524.         if(toDelete == null){  
    525.             return;  
    526.         }  
    527.         if(toDelete.next != null){          // 要删除的是一个中间节点  
    528.             toDelete.val = toDelete.next.val;       // 将下一个节点的数据复制到本节点!  
    529.             toDelete.next = toDelete.next.next;  
    530.         }  
    531.         else{       // 要删除的是最后一个节点!  
    532.             if(head == toDelete){       // 链表中只有一个节点的情况    
    533.                 head = null;  
    534.             }else{  
    535.                 Node node = head;  
    536.                 while(node.next != toDelete){   // 找到倒数第二个节点  
    537.                     node = node.next;  
    538.                 }  
    539.                 node.next = null;  
    540.             }  
    541.         }  
    542.     }  
    543.       
    544. }  
  • 相关阅读:
    Ceph 之RGW Cache
    Ceph 之RGW Pub-Sub Module
    Ceph 之RGW Data Layout
    RocksDB 之Write Ahead Log(WAL)
    Ceph 之 Background on http frontends
    Ceph 之Multisite 下的bucket reshard
    Ceph之PG数调整
    Ceph之对象存储网关RADOS Gateway(RGW)
    window mysql重启、忘记密码等操作
    selenium处理HTML5视频播放未能自动播放解决办法
  • 原文地址:https://www.cnblogs.com/lixuwu/p/5676154.html
Copyright © 2011-2022 走看看