Linked list of data structures

Source: Internet
Author: User

First, let's define the data structure of a linked list, as follows

1 public class Link {2     private int value, 3     private Link Next, 4 public     void Set_value (int m_value) {5         t His.value = m_value; 6     } 7 public     int Get_value () {8         return Value, 9     }10 public     void Set_next (Link m_next) {One         THIS.N ext = m_next;12     }13 public     Link Get_next () {         return next;15     }16}

  

With this data structure, we need a way to generate and output the linked list, where the values of each element in the list are random numbers.

The code to generate the linked list is as follows:

1 public     static Link init (int count, int maxValue) 2     {3         link list = new link (); 4         Link temp = list; 5
   
    random r = new Random (); 6         Temp.set_value (Integer.min_value); 7 for         (int i = 0; i < count; i++) 8         {9             link node = new link (); 10< C9/>node.set_value (R.nextint (MaxValue));             temp.set_next (node);             temp=node;13         }14         Temp.set_next (null);         return list;16     }17 public     static Link init (int count)     {20         return init (count, integer.max_value);     
   

  

For the head node of a linked list, we do not store any information, so set its value to Integer.min_value. We overloaded the method of generating the linked list.

Here's how to print the linked list information:

1 public     static void Printlist (Link list) 2     {3         if (list = = NULL | | List.get_next () = = null) 4         {5             Sys Tem.out.println ("The list is null or empty."); 6             return, 7         } 8         Link temp = List.get_next (), 9         stringbuffer sb = new StringBuffer (), ten while         (temp! = N ull)         {             sb.append (temp.get_value () + ");             Temp=temp.get_next ();         }15         System.out.println (sb.substring (0, Sb.length ()-2));     

  

Well, with these basic methods, we can delve into the list-related interview questions.

      • Linked list reversal
        Idea: There are two ways to implement a list reversal, the first is to loop each element directly, modify its next property, and the other is to take a recursive approach.
        First, let's look at the direct loop way:
1 public     static link reverve (link list) 2     {3         if (list = = NULL | | List.get_next () = = NULL | | list.get_next (). g Et_next () = null) 4         {5             System.out.println ("list is null or just contains 1 element, so does not need to reverve.") ); 6             return list; 7         }         8         link current = List.get_next (); 9         Link Next = Current.get_next ();         Current.set_next (null); one while         (Next! = null):         {             Link temp = Next.get_next ();             next.set_ Next (current):             next;16             next = temp;17         }18         list.set_next (current);         Return list;21     }

Then there is the recursive way:

1 public     static link recursivereverse (link list) 2     {3         if (list = = NULL | | List.get_next () = = NULL | | list.get _next (). Get_next () = = null) 4         {5             System.out.println ("list is null or just contains 1 element, so does not need to r Everve. "); 6             return list; 7         } 8          9         list.set_next (Recursive (List.get_next ()));         return list;12     }13     private static link Recursive (Link list) +     {         if (list.get_next () = = null)             list;20         }21         Link temp = Recursive (List.get_next ()),         List.get_next (). set_ Next (list),         list.set_next (null), and         return temp;

Outputs the element at the specified position (nth element in the bottom)
Idea: Using two cursors to traverse the list, the 1th cursor takes n steps first, and then two cursors advance simultaneously, and when the first cursor is last, the second cursor is the desired element.

1 public     static link find (Link list, int rpos) 2     {3         if (list = = NULL | | List.get_next () = = null) 4         {5
   return null; 6         } 7         int i = 1; 8         Link first = List.get_next (); 9         Link second = List.get_next (); ten while         (true) 11
   
    {12             if (I==rpos | | first = = NULL) break;13 First             = First.get_next ();             i++;15         }16         if (first = = NULL)             System.out.println ("The length of list is less than" + RpoS + ".");             return null;20         }21         while (First.get_next ()! = null): {at first             = First.get_next (); 24             second = Second.get_next ();         return second;28     }
   

Delete the specified node
Ideas: Can be discussed, if the specified node is not the tail node, then you can use trickery, the value of the specified node is modified to the value of the next node, the specified node's next property is set to Next.next, but if the specified node is a tail node, then it can only be traversed from the beginning.

1 public     static void Delete (link list, link element) 2     {3         if (Element.get_next ()! = null) 4         {5             Eleme Nt.set_value (Element.get_next (). Get_value ()); 6             Element.set_next (Element.get_next (). Get_next ()); 7         } 8         Else 9         {Ten             Link current = List.get_next (); one while             (Current.get_next ()! = Element)             {Current                 = Current.get_next ();             }15             Current.set_next (null);         }17     }

Delete duplicate nodes
Idea: Using Hashtable to access the elements in the list, traversing the linked list, when the element of the specified node already exists in Hashtable, then delete the node.

1 public     static void Removeduplicate (Link list) 2     {3         if (list = = NULL | | List.get_next () = = NULL | | list.get_ Next (). Get_next () = = null) return; 4         Hashtable table = new Hashtable (), 5         link cur = list.get_next (); 6         Link Next = Cur.get_next (); 7         TABLE.P UT (Cur.get_value (), 1); 8 while         (next = null) 9         {Ten             if (Table.containskey (Next.get_value ())) one by one             {                 cur.set_next ( Next.get_next ());                 Next = Next.get_next ();             }15             else16             {                 table.put (Next.get_value (), 1);                 cur= next;19                 next = next.get_ Next ();             }21}     

Looking for the middle node of the linked list
Idea: With two cursors, the first cursor advances two steps at a time, and the second cursor is further down each time, and when the first cursor is last, the second cursor is the middle position. It is important to note that if the number of linked list elements is even, then the intermediate element should be two.

 1 public static void Findmiddleelement (Link list) 2 {3 if (list = = null | | List.get_next () = = null) return; 4 System.out.println ("The middle element is:"); 5 if (List.get_next (). Get_next () = = null) 6 {7 System.out.println (List.get_next (). Get_value () ); 8} 9 Link fast = List.get_next (), Link slow = List.get_next (), one while (Fast.get_next ()             ! = null && fast.get_next (). Get_next ()! = null) # {14 fast = Fast.get_next (). Get_next (); slow = Slow.get_next ();}16 if (fast! = null && fast.get_next () = = null) 1 8 {System.out.println (Slow.get_value ());}21 Else22 {syste M.out.println (Slow.get_value ()); System.out.println (Slow.get_next (). Get_value ());}26} 

List element Ordering
Idea: The list element is sorted in two ways, one is the sort of the list element itself, and the other is the list element is worth sorting. The second approach is simpler and more flexible.

1 public     static void Sort (Link list) 2     {3         if (list = = NULL | | List.get_next () = = NULL | | list.get_next (). get_ Next () = null) 4         {5             return; 6         } 7         Link current = List.get_next (); 8         Link Next = Current.get_next (); 9 While         (current.get_next () = null) Ten         {one while             (Next! = null), (                 current.get_value () > Next.get_value ()) (                 = Current.get_value (),                     current.set_value (                     next.get_value ());                     Next.set_value (temp);                 }19                 next = Next.get_next ();             }21 Current             = Current.get_next () ;             next = Current.get_next ();         }24     }

Determine if the chain list has a ring, if any, find the first node on the ring
Idea: You can use two cursors to determine whether the linked list has a ring, a cursor runs fast, a cursor runs slowly. When a fast-running cursor catches up with a slow-running cursor, it indicates a ring; When the fast-running cursor runs to the tail node, it shows no loop.
as to how to find the first node, it can be divided into two steps, first determine a node on the ring, calculate the distance of the head node to the nodes and the distance of the node in the loop, and then set up two cursors, point to the head node and the nodes on the ring, and divide the distance (which is large, which cursor to move first Until two distances are equal), and finally move two cursors at the same time, the first one encountered is the first node in the ring.

 1 public static link getloopstartnode (link list) 2 {3 if (list = = NULL | | List.get_next () = = NULL | | lis T.get_next (). Get_next () = = null) 4 {5 return null; 6} 7 int m = 1, n = 1; 8 Link fast = List.get_next ();             9 Link slow = List.get_next (); max while (fast! = null && fast.get_next ()! = null) 11 {12             Fast = Fast.get_next (). Get_next (); slow = Slow.get_next (); if (fast = = slow) break;15  M++;16}17 if (fast! = Slow) * {return null;20}21 Link temp = fast;22 while (Temp.get_next ()! = fast) at $ {temp = Temp.get_next (); n++             ;}27 Link Node1 = list.get_next (); link Node2 = fast;29 if (M < n) 30 {31          for (int i = 0; i < n-m; i++): {node2 = Node2.get_next (); 34   }35}36 if (M > N) PNs {for (int i = 0; i < m-n; i++) 39 {40 Node1 = Node1.get_next ();}42}43 while (true)             De1 = = Node2) (break;48}49 node1 = Node1.get_next (); 50 Node2 = Node2.get_next ();}52 node1;54 55}

Determine if two linked lists Intersect
Idea: Determine whether the tail nodes of the two lists are the same, and if they are the same, they must intersect

1 public     static Boolean isjoint (link list1, link list2) 2     {3         if (List1 = = NULL | | list2 = NULL | | list1.get_ Next () = = NULL | | List2.get_next () = null) 4         {5             return false; 6         } 7         link node1 = list1; 8         link node2 = list2; 9         WH Ile (node1.get_next () = null) Ten         {one             Node1 = Node1.get_next ();         }13 while         (Node2.get_next ()! = NULL)         {             node2 = Node2.get_next ();         }17         return node1 = = node2;19     }

Merge two ordered linked lists
Idea: Create a new list, and then traverse two ordered linked lists at the same time, compare their size, and move the smaller list forward until one of the linked list elements is empty. All elements on the non-empty list are then appended to the new linked list.

 1 public static link merge (link list1, link list2) 2 {3 Link list = new link (); 4 List.set_value (Integer.min_value); 5 Link current1 = List1.get_next (); 6 Link Current2 = List2.get_next (); 7 Link current = list;             8 while (current1! = NULL && Current2! = null) 9 {Ten Link temp = new link (); 11 if (Current1.get_value () > Current2.get_value ()) {Temp.set_value (Current2.get_valu                 E ()); current2 = Current2.get_next ();}16 Else17 {18 Temp.set_value (Current1.get_value ()); current1 = Current1.get_next ();}21 C             Urrent.set_next (temp); current = Temp;23}24 if (current1! = null) 25 {26 while (current1! = null) ({)-Link temp = new link (); Temp.set_value (Curren T1.get_value ()); Current.set_next (temp); current = temp;32 Current1 = Curren T1.get_next ();}34}35 (Current2! = null) Notoginseng (curr Ent2! = null) for the new link (), Temp.set_value (Current2.get_valu E ()); Current.set_next (temp); current = temp;44 Current2 = current2.ge     T_next ();}46}47 current.set_next (null); }

Any two elements in the swap list (non-head nodes)
Idea: First you need to save the pre and next nodes of the two elements, and then reassign the next property of the pre node and next node, respectively. It is important to note that when the two elements are adjacent to each other, special processing is required, otherwise the linked list is trapped in a dead loop.

 1 public static void Swap (link list, link element1, link element2) 2 {3 if (list = = NULL | | list.get_nex T () = = NULL | |  List.get_next (). Get_next () = = NULL | | 4 Element1 = = NULL | | Element2 = = NULL | | Element1 = = Element2) 5 return; 6 7 Link Pre1 = null, Pre2 = NULL, NEXT1 = NULL, NEXT2 = NULL; 8 Link cur1=element1, Cur2=element2; 9 Link temp = List.get_next (); Boolean bFound1 = false;11 Boolean bFound2 = false;12 whi                 Le (temp! = null) (Temp.get_next () = = Cur1) (+ pre1=temp;17 Next1 = Temp.get_next (). Get_next (); bFound1 = true;19}20 if (temp.g                 Et_next () = = CUR2) {Pre2 = temp;23 next2 = Temp.get_next (). Get_next (); 24 Bfound2=true;25}26 if (bFound1 && bFound2) break;27             temp = Temp.get_next ();}29 if (cur1.get_next () = = Cur2) 31 {32 temp = Cur2.get_next (); Pre1.set_next (CUR2); Cur2.set_next (CUR1); cur1.set_ne             XT (temp);}37 else if (cur2.get_next () = = Cur1) (= Cur1.get_next (); 40 Pre2.set_next (CUR1); Cur1.set_next (CUR2); Cur2.set_next (temp);}44 E lse45 {pre1.set_next (CUR2); Cur1.set_next (NEXT2); Pre2.set_next (CUR1); 4 9 Cur2.set_next (NEXT1); 50}51}

Here, there is another way of trickery, which is to exchange the value of two elements directly without modifying the reference.

1 public     static void Swapvalue (link list, link element1, link element2) 2     {3         if (element1 = = NULL | | element2 = = null) 4         {5             return; 6         } 7         int temp = Element1.get_value (); 8         Element1.set_value (element2.get_ Value ()); 9         Element2.set_value (temp);     

  

Linked list of data structures

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.