One of the big summary of the interview: Java to fix the list of the interview problem __java

Source: Internet
Author: User
Tags static class

The list is a kind of problem which often appears in the interview, this article uses the Java to realize the common Link list related topic in the interview. This article mainly refers to the integration rewrite the "easy to handle the interview in the list of the topic" and "Algorithm encyclopedia (1) Single list" two masterpiece. The two implementations of the Great God are C and C #, because I prefer to use Java for interviewing, so rewrite all implementations in Java and attach some of my own thinking notes. Algorithm Encyclopedia (1) Single linked list has not yet been integrated into some issues, and soon I will update this article. Then there will be a big summary of the binary tree and a large sum of stacks and queues. Because these are in the interview to send the question. Must be scored without bias. As for the dynamic planning of these "high-end" algorithms, it can only rely on the cumulative, but not like this temporary raids.


Second: "Interview a big summary of the second: Java to fix the interview in the two-tree problem" has been released.



Package linkedlistsummary;
Import Java.util.HashMap;

Import Java.util.Stack; /** * http://blog.csdn.net/luckyxiaoqiang/article/details/7393134 Easy to handle the list of questions in the interview * http://www.cnblogs.com/jax/archive /2009/12/11/1621504.html algorithm Encyclopedia (1) Single link Table * Directory: * 1. Find the number of nodes in a single list: Getlistlength * 2. Reverse Single list: Reverselist (traversal), Reverselistrec (Recursive) * 3. Find the reciprocal k nodes in a single list (k > 0): Regetkthnode * 4. Find the middle node of a single list: Getmiddlenode * 5. Print a single list from the end of the head: Reverseprintliststack,reverseprintlistrec (Recursive) * 6. It is known that two single linked list PHead1 and pHead2 are in order, merging them into a list is still in order: Mergesortedlist, Mergesortedlistrec * 7. Determine if there is a ring in a single linked list: Hascycle * 8. Determine if two single linked lists intersect: Isintersect * 9. Find the first node where two single linked lists intersect: Getfirstcommonnode * 10. A ring in a single linked list is known to find the first node in the loop: getfirstnodeincycle, Getfirstnodeincyclehashmap * 11. A single linked table head pointer phead and a node pointer ptobedeleted,o (1) Time Complexity deletion node Ptobedeleted:delete */public class Demo {public static void main (S)
		Tring[] args {node N1 = new node (1);
		Node N2 = new node (2);
		node N3 = new node (3);
		Node N4 = new node (4);
Node N5 = new node (5);		N1.next = n2;
		N2.next = n3;
		N3.next = N4;

		N4.next = N5;
Printlist (N1);
System.out.println (Getlistlength (N1));
Node head = reverselist (n1);
Node head = Reverselistrec (n1);

		Printlist (head);
		Node x = Regetkthnode (n1, 2);
		System.out.println (X.val);
		
		
Regetkthnoderec (N1, 2);
x = Getmiddlenode (head);
System.out.println (X.val);
System.out.println ("Reverseprintliststack:");
Reverseprintliststack (head);
System.out.println ("Reverseprintlistrec:");

	Reverseprintlistrec (head); }//public static void main (string[] args) {//node N1 = new node (1);//node N2 = new node (3);//Node N3 = new N
Ode (5);
N1.next = n2;
N2.next = n3;
Node M1 = new node (1);
node m2 = new node (4);
Node M3 = new node (6);
M1.next = m2;
M2.next = m3;
//Node ret = mergesortedlist (n1, M1);
Printlist (ret);
		private static class Node {int val;

		Node Next;
		Public Node (int val) {this.val = val;
}
	}
	public static void Printlist (Node head) {while (head!= null) {System.out.print (Head.val + "");
		head = Head.next;
	} System.out.println (); //Find out the number of nodes in a single linked list//Check that the list is empty.
		Time complexity is O (n) public static int getlistlength (Node head) {//Note header node is empty if (head = = null) {return 0;
		int len = 0;
		Node cur = head;
			while (cur!= null) {len++;
		cur = cur.next;
	return Len;
	//Flip List (traversal)//traverse the original linked list, each traversal of a node,//Put it off at the top of the new list. Note that the linked list is empty and has only one node. The time complexity is O (n) public static node Reverselist (node Head) {//If the list is empty or has only one node, without reversing, return directly to the original linked table header if (head = = NULL | | head.next
		= = null) {return head; 		Node rehead = null;

		After inversion, the new linked table pointer Node cur = head; 		while (cur!= null) {Node precur = cur; 			Use Precur to hold the reference to the node to be processed cur = cur.next;	Cur updates to the next node Precur.next = Rehead; 			Update Next Reference Rehead = Precur to process the node;
	Rehead point to the previous node to process the node} return rehead; //Flip recursion (Recursive)//The essence of recursion is that you default Reverselistrec has successfully solved the child problem for you. But don't think about how it's going to work./Now just handle the current NoThe relationship between de and child problems.
	Finally, the whole problem can be solved satisfactorily.
	               /* Head 1-> 2-> 3-> 4 Head 1--------------|
	           4-> 3-> 2//Node Rehead = Reverselistrec (Head.next);
	           Rehead Head.next 4-> 3-> 2-> 1//head.next.next = head;
	           Rehead 4-> 3-> 2-> 1-> null//Head.next = NULL;
		Rehead */public static node Reverselistrec (node head) {if (head = = NULL | | head.next = NULL) {return head;	
		Node Rehead = Reverselistrec (Head.next);		Head.next.next = head;				Connect the head to the last back of the rehead string head.next = null;
	Prevent circulation list return rehead; /** * Find the reciprocal k nodes in a single list (k > 0) * The most common method is to first count the number of nodes in a single linked list and then find the first (n-k) node. Note that the list is empty and K is 0,k as 1,k is greater than the number of nodes in the list *. Time complexity is O (n). Code slightly.
	 Here is another idea, this kind of thinking in other topics will also be applied. * The main idea is to use two pointers, let the front pointer go to the K-node *, so the distance between the two pointers is k-1, followed by two pointers to go forward together, the front of the pointer to the last node, the following pointer to the node is the penultimate k node * * * public static N Ode REgetkthnode (Node head, int k) {//Here the Count of K is starting from 1, if K is 0 or the list returns null if (k = = 0 | | | head = = NULL) {return null; Node q = head; Q in front of P p--q Node p = head;
			P behind Q//Let Q lead p distance k while (k > 1 && q!= null) {q = Q.next;
		k--;
		//When the number of nodes is less than k, returns null if (K > 1 | | | = = NULL) {return null;
			The two pointers go together until the previous pointer points to the last node while (Q.next!= null) {p = p.next;
		Q = q.next;
	///When the previous pointer points to the last node, the following pointer points to the reciprocal K node return p;
	/** * Recursively prints the value of the reciprocal K-position * @param head * @param dist/static int level = 0;
        public static void Regetkthnoderec (Node head, int k) {if (head = = null) {return;
        } if (k = = 1) {return;
        } Regetkthnoderec (Head.next, k);
        level++;
        if (level = = k) {System.out.println (head.val); }//Find the middle node of a single list/** * This topic can be applied to a similar idea in the previous question. Also set two pointers, but here is, two pointers go forward at the same time, the front of the pointer two steps at a time, the back of the pointer one step at a time, * before the pointer to the last node, followed by the point of the pointer nodeIs the middle node, that is, the first (n/2+1) node. Note that the list is empty and the number of nodes in the linked list is 1 and 2.
		Time complexity O (n */public static node Getmiddlenode (node head) {if (head = = NULL | | head.next = NULL) {return head;		Node q = head;

		P---q Node p = head;
			The front pointer goes two steps at a time until it points to the last node, followed by one step at a time (q.next!= null) {q = Q.next;
			p = p.next;
			if (Q.next!= null) {q = Q.next;
	} return p; /** * Print a single linked list from the end * For this upside down sequence, we should think about the stack, LIFO first. Therefore, this topic either uses the stack on its own, or lets the system use the stack, which is recursion. Note the situation where the list is empty *.
		The time complexity is O (n) */public static void Reverseprintliststack (Node head) {stack<node> s = new stack<node> ();
		Node cur = head;
			while (cur!= null) {s.push (cur);
		cur = cur.next;
			while (!s.empty ()) {cur = S.pop ();
		System.out.print (Cur.val + "");
	} System.out.println (); /** * Prints a linked list from the end of the head, using recursion (elegance).
		) */public static void Reverseprintlistrec (Node head) {if (head = = null) {return;
			else {Reverseprintlistrec (head.next);
		System.out.print (Head.val + ""); }}/** * known twoSingle-linked lists PHead1 and PHead2 are ordered, merging them into a linked list that is still ordered * this sort of merge. Note in particular that all two lists are empty and one of them is empty. Only need O (1) of space. The time complexity is O (max (LEN1, len2))/public static Node mergesortedlist (node head1, node head2) {//Where one of the linked lists is empty, return directly to another linked header, O (
		1 if (head1 = = null) {return head2;
		} if (head2 = = null) {return head1;
		Node mergehead = null;
			First determine where Mergehead is where if (Head1.val < head2.val) {mergehead = Head1; 		Head1 = Head1.next; 	Skipping elements that have already been merged mergehead.next = NULL;
			Disconnect mergehead and back contact} else {mergehead = head2;
			Head2 = Head2.next;
		Mergehead.next = null;
		Node mergecur = Mergehead; 		 while (head1!= null && head2!= null) {if (Head1.val < head2.val) {mergecur.next = Head1;				 Merge the found smaller elements into the merge head1 = Head1.next;	 Skip the elements that have been merged mergecur = Mergecur.next;			 Find the next element to be merged mergecur.next = NULL;
				Disconnect mergecur and back contact} else {mergecur.next = head2;
				Head2 = Head2.next;
				Mergecur = Mergecur.next; Mergecur.next = null;
		///Merges the remaining elements if (head1!= null) {mergecur.next = Head1;
		else if (head2!= null) {mergecur.next = head2;
	return mergehead; /** * Recursive merge of two linked lists (elegance.
		*/public static node Mergesortedlistrec (node Head1, node head2) {if (head1 = = null) {return head2;
		} if (head2 = = null) {return head1;
		Node mergehead = null;
			if (Head1.val < head2.val) {mergehead = Head1;
		Connection Resolved child problem Mergehead.next = Mergesortedlistrec (Head1.next, head2);
			else {mergehead = head2;
		Mergehead.next = Mergesortedlistrec (Head1, Head2.next);
	return mergehead; /** * To determine if a single linked list has a ring * This also uses two pointers. If there is a link in a list, that is, a pointer to traverse, is never go to the end. Therefore, we can use two pointers to traverse, a pointer to take two steps at a time *, a pointer one step at a time, if there is a ring, two pointers will certainly meet in the ring. Time complexity is O (n)/public static Boolean hascycle (node Head) {node fast = head;//quick pointer each step forward two Node slow = head;//slow pointer each time
			Previous while (Fast!= null && fast.next!= null) {fast = Fast.next.next;
			slow = Slow.next; if (fast = = slow) {//phaseIn the event of a ring return true;
	return false; //Determine if two single linked lists intersect/** * If two lists intersect a node, then all nodes after the intersection node are shared by two lists.
	 That is, if two linked lists Intersect, then the last node is definitely common. * First to traverse the first linked list, remember the last node, and then traverse the second linked list, to the last node and the first list of the last node to compare, if the same, then intersect, * otherwise not intersect. The time complexity is O (len1+len2) because only one extra pointer is needed to save the last node address, and the space complexity is O (1)/public static Boolean Isintersect (node head1, node head2) {i
		F (head1 = null | | head2 = NULL) {return false;
		Node tail1 = head1;
		Find the last node in List 1 while (Tail1.next!= null) {tail1 = Tail1.next;
		Node tail2 = head2;
		Find the last node in List 2 while (Tail2.next!= null) {tail2 = Tail2.next;
	return tail1 = = TAIL2;
	 /** * asks the first node of two single linked lists to traverse the first linked list, compute the length len1, and save the address of the last node.
	 * Iterate over the second list, calculate the length len2, and check that the last node is the same as the last node of the first linked list, and if not, does not intersect and ends.
	 * Two linked lists start from scratch, assuming that len1 is greater than len2 *, then the first linked list is first traversed LEN1-LEN2 nodes, at this point, two list the current node to the first intersection node is the same distance, and then iterate backwards, until two nodes of the same address.
	 * Time complexity, O (LEN1+LEN2) * *----LEN2 * |__________ * | *---------LEN1 * |---|&Lt;-Len1-len2 */public static Node Getfirstcommonnode (node head1, node head2) {if (Head1 = null | | head2 = NULL)
		{return null;
		int len1 = 1;
		Node tail1 = head1;
			while (Tail1.next!= null) {tail1 = Tail1.next;
		len1++;
		int len2 = 1;
		Node tail2 = head2;
			while (Tail2.next!= null) {tail2 = Tail2.next;
		len2++;
		The//disjoint directly returns NULL if (Tail1!= tail2) {return null;
		Node n1 = Head1;

		Node n2 = head2;
			Skip over longer list superfluous parts if (Len1 > Len2) {int k = len1-len2;
				while (k!= 0) {n1 = N1.next;
			k--;
			} else {int k = LEN2-LEN1;
				while (k!= 0) {n2 = N2.next;
			k--;
			}//to traverse backward together until the intersection is found (N1!= n2) {n1 = N1.next;
		N2 = N2.next;
	return N1; /** * Seek the first node in the loop to do with the speed pointer (this is the crack coding interview solution, because it is more concise and understandable.
		) */public static node Getfirstnodeincycle (node Head) {node slow = head;

		Node fast = head; 1 Find the quick and slow pointer meet point while (fast!= null && fast.next!= NULL) {slow = Slow.next;
			Fast = Fast.next.next;
			if (slow = = fast) {//Collision break;
		}//Error checking, this is no loop condition if (fast = NULL | | fast.next = NULL) {return null;
		}//2) Now, the distance from the beginning of the ring is equal to the distance between the head of the chain and the beginning of the ring,//So, we put the slow pointer on the head of the chain, the quick pointer remains at the meeting point, then//the same speed forward, again meet the point is the beginning of the ring
		slow = head;
			while (slow!= fast) {slow = Slow.next;
		Fast = Fast.next;
	//Again meet point is the beginning of the ring return fast;
	 /** * To enter the first node in the ring with HashMap to do a ring-free list, it is the address of each node is not the same.
	 * But if there is a ring, the pointer moves along the linked list, and the pointer ends up pointing to an address that has already been addressed with the key value of the hash table, with each occurrence of an address, the value of the key corresponding to the real value is set to true. * Then when the value of a key value is already true, this address has already appeared before, and it is OK to return it directly. */public static node Getfirstnodeincyclehashmap (node head) {Hashma
		P<node, boolean> map = new Hashmap<node, boolean> (); while (head!= null) {if (map.get) = = True) {return head;//This address has already appeared before, that is, the beginning of the ring} else {Map.put (he
				AD, True);
			head = Head.next;
	} return head; /** * gives a single chain header pointer head and a node pointer tobedeleted,o (1) Time Complexity Delete node tbedeleted * For delete nodes, we are normalThe idea is to have the previous node of the node point to the next node of the node *, which requires traversing the previous node to find the node, with a time complexity of O (n). For a linked list, the structure of each node in the list is the same, so we can copy the data from the next node of the node to the node * and then delete the next node. To be aware of the last node, this can only be done in a common way, first to find the previous node, but the overall average time complexity is still O (1)/public void Delete (node Head, node Todelete) {if (todelete
		= = null) {return;		} if (Todelete.next!= null) {//To be deleted is an intermediate node todelete.val = toDelete.next.val;
			Copy the data from the next node to this node!
		Todelete.next = ToDelete.next.next;
			else{//Is the last node to be deleted.
			if (head = = Todelete) {//list only one node in the case head = NULL;
				}else{node node = head;
				while (Node.next!= todelete) {//Find the penultimate node = Node.next;
			} node.next = null;
 }
		}
	}
	
}




Thank you, @buding12321, that bug~ has been repaired.


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.