Programmer programming Art: Chapter 9 catch up with gossip linked lists

Source: Internet
Author: User

Prelude
There is a problem: You can choose two points on a straight track placed horizontally between the left and right, and place two robots. Use the following command system to design a control program for the robot, this allows the two robots to meet on a straight track. (Note that the two robots are controlled using the same program you wrote ).
Command System: contains only four commands, including left-to-right, condition determination, and unconditional jump. The left (right) command can be used to control the robot to move one step to the left (right). The condition determination command can be used to test the robot's position, the test result is that if the target robot has been here, true is returned; otherwise, false is returned; unconditional jump is similar to the jump in the Assembly, which can jump to any place.

OK. This interesting answer is the question of the Microsoft Engineering Institute last year. The answer will be provided at the end of this article (if you are eager to know the answer to this question, you can skip to Section 3 of this Article ). At the same time, we can see that this question is a typical catch-up question. Which of the following questions is the catch-up question common? By the way, linked lists catch up. This chapter describes this issue. If there is something wrong, I hope you can correct it.


Section 1: Calculate the k-th node at the bottom of the linked list
13th question and description:
Enter a one-way linked list and output the last k nodes in the list,
The last 0th nodes of the linked list are the tail pointer of the linked list.

Analysis: as a result, I believe that comrades with a little experience will all say: Set the two pointers p1 and p2. First, both p1 and p2 point to the head, and then p2 moves forward in k steps, in this way, k nodes are separated between p1 and p2, and p1 and p2 move forward simultaneously until p2 reaches the end of the linked list.

A friend reminded me a few days ago that, let me talk about this kind of problem about the k-node reciprocal of the linked list. I think people with some experience have already understood this problem, but they simply use two pointers to move forward one by one. However, he reminded me that if the interviewer did not have this consciousness, he would not think of it.

So how should we strengthen our awareness of this aspect during the interview preparation process? I think, in addition to having an interview question at ordinary times, I try to solve it with a variety of ideas to extend my horizons. In addition, I usually intentionally observe my life. Because, I believe, you can easily understand that, in fact, the catch-up problem of this linked list comes from the live long-distance race. If you pay more attention to thinking and accumulating, you can discover and appreciate your life, I believe it will also be helpful for the interview.

OK. The following is the subject code for this question:

Struct ListNode
{
Char data;
ListNode * next;
};
ListNode * head, * p, * q;
ListNode * pone, * ptwo;

// @ Heyaming. In the first section, consider the case where k is greater than the length of the linked list to find the last k node of the linked list.
ListNode * fun (ListNode * head, int k)
{
Assert (k> = 0 );
Pone = ptwo = head;
For (; k> 0 & ptwo! = NULL; k --)
Ptwo = ptwo-> next;
If (k> 0) return NULL;
 
While (ptwo! = NULL)
{
Pone = pone-> next;
Ptwo = ptwo-> next;
}
Return pone;
}

Extension:
This is the last k node in the chain list. Q: What if the linked list is bidirectional and there may be loops? See section 2. Program to determine whether two linked lists are intersecting.


Section 2: Determine the intersection of two linked lists by programming
Topic Description: two head pointers for one-way linked lists are provided, as shown in ),

For example, h1 and h2, determine whether the two linked lists are intersecting. To simplify the problem, we assume that both linked lists do not have loops.

Analysis: this is an interview question from the Microsoft sub-institution in the beauty of programming. Please follow my ideas step by step (some text comes from the beauty of programming ):

Judge whether each node of the first linked list is in the second linked list. However, the time complexity of this method is O (Length (h1) * Length (h2 )). Obviously, we have to find a more effective method, at least not the complexity of O (N ^ 2.
Create a hash table for the first linked list, query the hash table, and determine whether each node of the second linked list appears in the hash table, if all the nodes of the second linked list can be found in the hash table, it means that the second linked list has the same node with the first linked list. The time complexity is linear: O (Length (h1) + Length (h2). to store all nodes in the first linked list, the space complexity is O (Length (h1 )). Is there a better way to solve problems with linear time complexity and reduce storage space?
To further consider this feature, we can know that if two linked lists without loops overlap with a node, then all nodes after this node are shared by two linked lists, then the last node must be in total. However, we can easily get the last node of the linked list, which becomes a major breakthrough in simplifying the solution. Then, we only need to judge whether the tail pointers of the two linked lists are equal. Otherwise, the linked list does not.
Therefore, traverse the first linked list first and remember the last node. Then traverse the second linked list and compare it with the last node of the first linked list. If the two nodes are the same, they will be the same. Otherwise, they will not be the same. In this way, we get a time complexity, which is O (Length (h1) + Length (h2), and uses only one additional pointer to store the last node. The time complexity of this method is linear O (N), and the space complexity is O (1), which is obviously better than solution 3.
The above problems are all for the linked list without loops. What if the linked list has Loops now? Can we still find the last node for determination? Is the above method equally valid? Obviously, the nature of this problem has been transformed into determining whether a linked list has loops. So how can we determine whether a linked list has a ring?
Summary:
Therefore, in fact, the question of determining whether two linked lists are at the same intersection is transformed:
1. First, judge whether a belt or no ring exists.
2. If none of them contain loops, determine whether the end node is equal.
3. If both nodes contain loops, determine the node on which the two pointers meet on a linked list. The node is not on the other linked list.
If yes, It is intersecting. If not, it is not.

1. So, how do I write code to determine if the linked list has loops? Because in many cases, after you give a question, the interviewer may need to append your code, OK, as shown below (set two pointers (p1, p2), and the initial values all point to the header, p1 advances one step at a time, p2 advances two steps at a time. If the linked list has a ring, p2 first enters the ring, p1 enters the ring, and the two pointers move around in the ring, which must meet each other ):

View plaincopy to clipboardprint?
// Copyright @ KurtWang
// July and 2011.05.27.
Struct Node
{
Int value;
Node * next;
};

// 1. First, judge whether a belt or no ring exists.
// Determine whether a ring exists. bool is returned. If a ring exists, the node in the ring is returned.
// Train of thought: Use two pointers, one pointer step is 1, and the other pointer step is 2 to determine whether the linked list has loops.
Bool isCircle (Node * head, Node * & circleNode, Node * & lastNode)
{
Node * fast = head-> next;
Node * slow = head;
While (fast! = Slow & fast & slow)
{
If (fast-> next! = NULL)
Fast = fast-> next;

If (fast-> next = NULL)
LastNode = fast;
If (slow-> next = NULL)
LastNode = slow;

Fast = fast-> next;
Slow = slow-> next;

}
If (fast = slow & fast & slow)
{
CircleNode = fast;
Return true;
}
Else
Return false;
}
// Copyright @ KurtWang
// July and 2011.05.27.
Struct Node
{
Int value;
Node * next;
};

// 1. First, judge whether a belt or no ring exists.
// Determine whether a ring exists. bool is returned. If a ring exists, the node in the ring is returned.
// Train of thought: Use two pointers, one pointer step is 1, and the other pointer step is 2 to determine whether the linked list has loops.
Bool isCircle (Node * head, Node * & circleNode, Node * & lastNode)
{
Node * fast = head-> next;
Node * slow = head;
While (fast! = Slow & fast & slow)
{
If (fast-> next! = NULL)
Fast = fast-> next;

If (fast-> next = NULL)
LastNode = fast;
If (slow-> next = NULL)
LastNode = slow;

Fast = fast-> next;
Slow = slow-> next;

}
If (fast = slow & fast &

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.