Common linked list questions (java Edition)

Source: Internet
Author: User
Tags table definition

Common linked list questions (java Edition)

Dry goods directly .....

Common linked list questions:

Find the last k nodes of a single-chain table. Delete a node (O (1) in a single-chain table )). Reverse the linked list. The first public node of the two linked lists. The Start Node of the loop returned from the chain table (and whether the ring exists ). Merge two sorted linked lists. Delete duplicate nodes in the linked list.

First, the definition of the linked list is given:

/*** Single-chain table definition */public static class Node
  
   
{Private E element; // The elements saved by the Node private Node
   
    
Next; // reference to the next Node public Node () {} public Node (E element) {this. element = element;} public Node (E element, Node
    
     
Next) {this. element = element; this. next = next;} public E getElement () {return element;} public Node
     
      
GetNext () {return next;} public void setElement (E element) {this. element = element;} public void setNext (Node
      
        Next) {this. next = next ;}}
      
     
    
   
  

Robustness:

Robustness also becomes robustness, which means that the program can judge whether the input meets the standard requirements and properly process the input that does not meet the requirements. Fault tolerance is an important embodiment of robustness. An Effective Way to Improve code robustness is to implement defensive programming. Defensive Programming is a programming habit that predicts where problems may occur and develops solutions for these problems. During the interview, the most common and most effective defensive programming is to add code at the function entry to verify that user input meets the requirements.

1. Find the last k nodes of a single-chain table.

Assume that the last node is the last one. Thought: Speed pointer. The implementation code is as follows:

Public static Node
  
   
Solution (Node
   
    
Head, int k) {// determine whether k is illegal if (k <1) {return null;} // determine whether it is null if (head = null) return null; // fast pointer Node
    
     
NAhead = head; // slow pointer Node
     
      
NBehind = head; // fast pointer first K-1 step for (int I = 0; I
      
     
    
   
  
Function test: the k-th node is in the middle, and the first node is in the end node. Special test: the header node is null, k is 0, and the number of nodes is less than k time complexity: O (n), space complexity: O (1) 2. delete a node (O (1) in a single-chain table )).

Suppose you can only access this node. Idea: swap location. The implementation code is as follows:

// You do not know the header node and cannot delete the end node. Public static boolean solution (Node  Node) {// if (node = null) return false when the node is empty; // The node is the last node if (node. getNext () = null) return false; Node  Temp = node. getNext (); // exchange node storage data node. setElement (temp. getElement (); node. setNext (temp. getNext (); return true ;}  

Note: If you know the header node, you can ensure that the average time complexity is O (1 ). If you do not know whether you want to delete the end node from the header node, you can only mark the end node.

3. Reverse linked list

The Code is as follows:

Public static Node  Solution (Node  Head) {// the header node is empty if (head = null) return head; // only one node if (head. getNext () = null) return head; // records the Node that is finally reversed  Temp1 = head; // record the Node to be reversed  Temp2 = head; // record the next Node of the Node to be reversed  Temp3 = head. getNext (); while (temp3! = Null) {temp2 = temp3; temp3 = temp2.getNext (); temp2.setNext (temp1); temp1 = temp2;} head. setNext (null); head = temp1;/* while (temp1! = Null) {System. out. print (temp1.getElement () +,); temp1 = temp1.getNext () ;}*/return head ;}     

Note: When calling a method, we can directlysolution(head);Then print the head pointing to the linked list... Actually, you know, I am a cainiao .....
Okay, here.solution(head)The method passes the reference of the head, so when the head is executed, it still points to the first node, that is, the last node...

The first public node of two non-ring linked lists.

The Code is as follows:

Public static Node  Solution (Node  Head1, Node  Head2) {// empty if (head1 = null | head2 = null) return null; // same linked list, no longer need to calculate the length if (head1 = head2) return head1; // calculate the length difference int length1 = 0; int lengh2 = 0; Node  Temp1 = head1; Node  Temp2 = head2; while (temp1.getNext ()! = Null | temp2.getNext ()! = Null) {if (temp1.getNext ()! = Null) temp1 = temp1.getNext (); else length1 ++; if (temp2.getNext ()! = Null) temp2 = temp2.getNext (); else length1 ++;} temp1 = head1; temp2 = head2; // linked list 1 long, linked list 1 first length1 step if (length1! = 0) {// execute step length1 for (int I = 0; I      
Test: Non-intersection, same, intersection in the middle, intersection at the end, null; time complexity: O (max (m, n); The above code is not well reused, the same part can be written as another method. Extension: The linked list has loops. 5. the Start Node of the loop returned from the chain table.

Or the length of the ring, or the total number of nodes. The Code is as follows:

Public static Node  Solution (Node  Head) {// defines two Node variables, one taking two steps at a time and one taking one Node at a time.  AheadNode = head; Node  BehindNode = head; // locate the first encounter while (aheadNode. getNext ()! = Null) {aheadNode = aheadNode. getNext (). getNext (); behindNode = behindNode. getNext (); if (behindNode = aheadNode) break;} // The Slow node points to the head, and then the two pointers take one step at a time behindNode = head; while (behindNode! = AheadNode) {behindNode = behindNode. getNext (); aheadNode = aheadNode. getNext () ;}return behindNode ;}    
Test: NULL, the ring formed by a node, the ring formed by the intermediate node, and the last Ring Formed without a ring; time complexity: O (n ).

Derivative Problems:

/*** Determine whether the linked list has a ring * idea: the speed pointer is implemented, and if there is a ring, it will surely intersection. **/Public static boolean checkCircuit (Node  Head) {// if (head = null) return false; // defines two nodes, one fast Node and one slow Node.  AheadNode = head; Node  BehindNode = head; // never judge two at a time: behindNode. getNext (). getNext ()! = Null while (behindNode. getNext ()! = Null) {behindNode = behindNode. getNext (). getNext (); if (behindNode = null) return false; aheadNode = aheadNode. getNext (); if (behindNode = aheadNode) return true;} return false ;}   
Test: NULL. The ring formed by a node, the ring formed by the intermediate node, and the last Ring Formed without a ring. Time Complexity: O (n) 1. Why can a fast/slow pointer determine whether or not it is intersecting?

One pointer a takes one step at a time, and the other pointer B takes two steps at a time. Without a ring, you cannot catch up with it.
Currently, the following three situations exist:

A is a node before B, B is a node before a, and a and B are met.

Obviously, the third case naturally proves that there are loops, 1st and 2nd.

<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4NCjxoNCBpZD0 = 2. Why does a point to the head after the meeting, and then a and B are both the first public node each time they encounter?

For details, see:

6. merge two sorted linked lists.

Two implementations: recursive and non-recursive.

7. Delete duplicate nodes in the linked list.

There are two kinds of questions:

Repeat only one
Public static Node  Solution (Node  Head) {// empty if (head = null) return head; Node  Ahead = head; Node  Curr = head. getNext (); while (curr! = Null) {if (ahead. getElement () = curr. getElement () // Delete ahead if the same. setNext (curr. getNext (); else ahead = curr; // different postshift curr = curr. getNext (); // The current pointer is moved back regardless of whether the pointer is the same or not} return head ;}    
Retained
Public static Node  Solution2 (Node  Head) {// empty if (head = null) return head; // Node to be determined  Curr = head. getNext (); // Node of the previous Node of curr  Ahead = head; // record the previous Node of ahead  PreAhead = null; // record whether the ahead node has repeated boolean needDelete = false; while (curr! = Null) {// Delete if (ahead. getElement () = curr. getElement () {ahead. setNext (curr. getNext (); needDelete = true;} else {if (needDelete) {// The ahead node must be deleted again. Replace the previous node with the last one, and then set the next node of the preAhead. // If preAhead is set directly, the ahead cannot be processed when the repeat starts. setElement (curr. getElement (); ahead. setNext (curr. getNext (); needDelete = false;} else {// different postshift preAhead = ahead; ahead = curr ;}// whether the current pointer is the same or not, move curr = curr. getNext () ;}if (needDelete) {// if all are equal, null if (preAhead = null) {return null;} is returned ;} // otherwise, the last node needs to delete preAhead. setNext (null);} return head ;}     
Test: all equal, equal at the beginning, equal at the end, and equal in the middle; time complexity: O (n); problem summary: pay more attention to the start condition when considering the problem, for example, if preAhead is set to null at the beginning, you must consider whether there is a value assignment to it. Otherwise, an error occurs.

 

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.