Java How to write a list program __java

Source: Internet
Author: User
Tags int size

recently in the training of ACM in C language to write a lot of linked list program. Because recently learning Java, so I want to write a list of Java program, the result encountered a lot of difficulties. The following article is a good summary of the entire process of writing, worth collecting.

1, single linked list creation and traversal

2, to find the number of nodes in a single linked list

3, find a single linked list in the penultimate K node (sword refers to offer, question 15)

4. Find the middle node in single linked list

5, the merger of two orderly single linked list, after the merger of the linked list is still orderly "high frequency" (sword refers to offer, question 17)

6, single linked list of the reverse "frequency of the highest" (sword refers to offer, question 16)

7, delete the duplicate elements in a single linked list

8, from the end of the print single linked list (sword refers to offer, question 5)

9, to determine whether a single linked list has a ring

10, take out the chain list, the length of the ring

11, single linked list, take out the starting point of the ring (sword refers to offer, question 56). Use the above 8th question and the 9th question.

12, to determine the first intersection of two single linked table (sword refers to offer, question 37)

1, the single linked list creation and traversal:

public class linklist{public Node head;
	
	public Node Current; Methods: Add Data public void Add (int data) to the linked list {//To determine if the list is empty if (head = = null) {//If the header node is empty, to show that the list has not yet been created, assign the new node to the head node. He

			ad= new Node (data);
		current = head;

			else{//Create a new node, put it behind the current nodes (associate the new knot with the linked list) Current.next = (data); Move the current index of a linked list backward by one present = Current.next; After this step is complete, the current node points to the newly added node}//Method: Traversing the list (printout list).
		
		The parameter of the method represents the start of traversal of public void Print (node node) {if (node = null) {return;

		Current = node;	

			while (current!= null) {System.out.println (current.data);

		current = Current.next;

		Class Node {//NOTE: The two member variable permissions here cannot be private because private permissions are only accessible to this class.
		
		int data;//data domain node next;//pointer domain public node (int data) {this.data = data; } public static void Main (string[] args) {linklist list = new linklist ();//Add data to linklist for (int i = 0; i < i++)
		        
	{List.add (i);			} list.print (List.head);//start traversing output} from head node 

in the upper code, the node node in this box is represented by an inner class (60 lines). The biggest benefit of using an inner class is that it can be accessed by private operations with external classes.

Note: Internal class access is characterized in that an inner class can directly access members of an external class, including private; an external class must first create an object to access the members of the inner class.

To facilitate the addition and traversal of operations, add a member variable current to the Linklist class that represents the index (05 rows) of the active node.

In this method of traversing the list (36 rows), the parameter node represents the traversal from the node nodes and does not necessarily traverse from the head node.

2, to find the number of nodes in a single linked list:

Note Check to see if the list is empty. Time complexity is O (n). This is relatively simple.

Core code:

Method: Gets the length of the single linked list

	int getlength (Node head) {

		if (head = = null) {return
	
			0;
	
		}


		int length = 0;

		Node current = head;

		while (current!= null) {

			length++;

			current = Current.next;

		}


		return length;

	}


3. Find the reciprocal K-knot in a single chain list:

3.1 General Ideas:

Iterate through the entire list first, calculate the length of the linked list size, get the length of the list, it is good to do, direct output (size-k) nodes can be (note that the list is empty, K is 0,k to 1,k than the number of nodes in the list)

)。 Time Complexity of O (n), the general idea is as follows:

	public int Findlastnode (int index) {//index represents the last node of the penultimate index


		//First traversal, gets the length of the list size

		if (head = = null) {

			return-1;

		}

		int size=0;

		current = head;

		while (current!= null) {

			size++;

			current = Current.next;

		}



		The second traversal, the output data current = Head of the penultimate index node

		;

		for (int i = 0;i < Size-index; i++) {Current

			= Current.next;

		}



		return current.data;

	}


If the interviewer doesn't allow you to traverse the length of the list, what do you do? The next thing is.

3.2 Improvement idea: (this kind of idea also has the application in other topics)

Here we need to declare two pointers: two node-type variables first and second, start with the first and second all point to the initial node, then let the second node k-1 the position, at which time the primary and second are separated by the k-1 position, The entire two nodes are then moved backwards until the second node is at the last point where the first node points to the position of the reciprocal K node. Time Complexity of O (n)

Code implementation: (first edition)

	Public node Findlastnode (node Head, int index) {

		if (head = = null) {return

			null;

		}

	 

		Node-A-head;

		Node second = head;

		Let the second node move back to the index position for

		(int i= 0;i < index; i++) {

			second = Second.next;

		}

	 

		Allow the second node to move backwards until the second node is null while

		(second!= null) {i

			= First.next;

			second = Second.next;

		}

	 

		When the second node is empty, the node that is pointed to at this point is the node that we are looking for.

	
 


Code implementation: (Final Version) (throws an exception when K is greater than the number of nodes in the list)

In the code above, it seems to have implemented functionality, but it's not robust enough:

Note that k equals 0;

If k is greater than the number of nodes in the list, a null pointer exception is reported, so there needs to be a judgment.

The core code is as follows:

	Public node Findlastnode (node head, int k) {  
		  
	    if (k = = 0| | head = = NULL) {return  
	  
	        null;  
	  
	    }  
	  
	  
	  
	    Node-A-head;  
	  
	    Node second = head;  
	  
	  
	  
	    Let the second node move back k-1 position for  
	  
	    (int i = 0; i < k-1; i++) {  
	  
	        System.out.println ("I's value is" + i);  
	  
	        second = Second.next;  
	  
	        if (second = = null) {//Description K's value is already greater than the length of the list  
	  
	            //throw  
	            new NullPointerException ("The length of the list is less than" + K);//We throw the exception ourselves, giving the user a hint return  
	  
	            null;  
	  
	        }  
	  
	    }  
	    
	    Move the first node back k-1 position for
	    (int i=0 i < k-1;i++) {
	    	
	    	first=first.next;
	    
	    }
	    
	    Return first;//Returns the value of the top of this point, which is the value to find.

	


4. Find the middle node in single linked list:

Similarly, the interviewer does not allow you to calculate the length of the linked list, how to do it.

Ideas:

As in the 2nd section above, it is also set two pointers first and second, but here is, two pointers go forward at the same time, the second pointer goes two steps at a time, and the first pointer goes one step at a time until the second pointer goes to the last node. At this point, the node in the "One" is the middle node. Note that the list is empty and the number of nodes in the linked list is 1 and 2. Time complexity is O (n).

Code implementation:

	Method: Find the middle node of the list public

	node Findmidnode (node head) {
	 

		if (head = = null) {return

			null;

		}

		Node-A-head;

		Node second = head;

		Each time you move, let the second node move two bits, and the first node moves a while

		(second!= null&& second.next!= null) {A/

			first.next;

			second = Second.next.next;

		}

		Until the second node is moved to NULL, the position at which the beginning pointer points is the position of the middle node return a.

	

In the upper code, when n is an even number, the resulting intermediate node is N/2 + 1 nodes. For example, when a list has 6 nodes, it gets the 4th node.

5, combined with two ordered single linked list, the merged list is still in order:

The problem is often inspected by the companies.

For example:

List 1:

1->2->3->4

List 2:

2->3->4->5

After merging:

1->2->2->3->3->4->4->5

Ideas for solving problems:

Compare list 1 and List 2 next to each other.

This is similar to merge sort. In particular, note that all two lists are empty and one of them is empty. Only need O (1) of space. Time Complexity of O (max (len1,len2))

Code implementation:

	The two parameters represent the header node of two linked lists public node mergelinklist (node Head1, node head2) {if (Head1 = = null&& Head2 = null) {

		If all two lists are null return null;

		} if (head1 = = null) {return head2;

		} if (head2 = = null) {return head1; Node Head; Node current of head node of new linked list;

			The current node points to the new list//At the beginning, we let the head1 point to the smaller data in the head2, and get the head node if (Head1.data < head2.data) {head = Head1;

			current = Head1;

		Head1 = Head1.next;

			} else{head = head2;

			current = Head2;

		Head2 = Head2.next; while (head1!= null && head2!= null) {if (Head1.data < head2.data) {current.next = Head1;/ /new Linked list, the next node of the current pointer corresponds to the smaller one of that data, current.next;

			The current pointer moves down head1 = Head1.next;

				} else{current.next = head2;

				current = Current.next;

			Head2 = Head2.next;

		///merge remaining elements if (head1!= null) {//Description List 2 traversed, is empty current.next = Head1; } if (head2!= null) {//Description list 1 traversal over, is empty current.next = head2;

	return head;
  }


Code test:

public static void Main (string[] args) {

		linklist list1 = Newlinklist ();

		Linklist list2 = Newlinklist ();

		Add data to linklist for

		(int i = 0; i < 4; i++) {

			list1.add (i);

		}

			 

		for (int i = 3; i < 8; i++) {

			list2.add (i);

		}

			 
		linklist list3 = Newlinklist ();

		List3.head = List3.mergelinklist (List1.head, List2.head); Merge List1 and list2 into List3

		list3.print (list3.head);//start traversing output from head node

	
 


The Add method and the Print method used in the upper code are consistent with the 1th section.


6, single linked list of the reverse:

	 public static node reverse (node Head)  
	    {  
	        if (null = head)  
	        {return  
	           null; 
	        }  
	        Node pre = head;  
	        Node cur = head.next;  
	        Node Next;  
	        while (null!= cur)  
	        {  
	            next = Cur.next;  
	            Cur.next=pre;  
	            Pre = cur;  
	            cur = next;  
	  
	        The next node of the first node of the original list is set to NULL, then the inverted head node is assigned to  
	        Head.next=null.  
	        return pre;
	    }  

}


6, delete the duplicate elements in a single list:

	public static int deletedupsnew [Node Head] {  
	    if (head = = null) return 0;  
	    Node current = head;
	    int x=0;
	    while (current!= null) {  
	        Node runner = current;  
	        while (Runner.next!= null) {  
	            if (Runner.next.data = = current.data) {  
	                runner.next = Runner.next.next;
	                x + +;
	            }  
	            else{  
	                runner = Runner.next  
	            }  
	        }  
	        current = Current.next;  
	    }
	    return x;
	}


Related Article

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.