Linked List and array of data structures (III)-simple operations on one-way linked list

Source: Internet
Author: User
4. Reverse the one-way linked list (non-Recursive Implementation)

Ideas:

Figure 1 Non-recursive reverse linked list

1. If the previous nodes have been reversed, and the first node pointer of the chain table is pre, you must first save the linked list after the current node cur, then, disconnect the cur pointer of the current node from the subsequent node (step 1). Next, point the next pointer of the current node to the first node pre (step 2) of the forward linked list ). After the current node's connection is reversed, all pointers are moved to the backend. Start processing the next node.

Note:

1. After reversing, the original head node becomes the End Node of the inverted linked list. Be sure to set the next pointer of this node to null. Otherwise, an endless loop may occur.

2. Remember to process a linked list with no nodes or only one node.

CodeImplementation:

// Reverse linked list (non-recursive) // input parameter: Header pointer of a single-chain table // output parameter: NONE // return value: singlelist * reverse_nrecu (singlelist * head) {singlelist * Pre, * cur, * Lat; // No node in the linked list or only one node if (Head = NULL) | (Head-> next = NULL) {return head;} Pre = head; cur = head-> next; head-> next = NULL; // handle the boundary condition in the linked list. The End Node must be empty. LAT = cur-> next; while (LAT! = NULL) {cur-> next = pre; Pre = cur; cur = Lat; lat = lat-> next;} cur-> next = pre; return cur ;}
5. Reverse the one-way linked list (Recursive Implementation)

Ideas:

When using recursion to implement the problem, we should always pay attention to the need to analyze the relationship between the first and second layers during analysis. Don't keep thinking down with recursion. If there are too many layers to consider, you may get stuck and get confused. Another special note in recursion is the termination condition of recursion. Make sure you understand when and how it ends.

Reverse query of the linked list:

Figure 2 Recursive Implementation of reverse linked list

When considering the relationship between the first and second layers, we assume that the chain table after the second layer has been processed, and it returns the tail pointer of the chain table, 2 (the nodes in the blue box are the nodes to be recursive. When considering the first layer, we assume they have been successfully reversed ). At this time, we only need to direct the next of the returned pointer cur to the current pointer, and then the current node is reversed. After the reverse operation, the pointer pre added to the reverse link is returned.

Another consideration is the recursion termination condition. The problem is that when recursion is reached to the last node, there are no nodes after it. This is a direct return.

Code implementation:

 
// Reverse linked list (recursive) // input parameter: first pointer of a single-chain table // output parameter: New pointer after reverse linked list // return value: the last pointer singlelist * reverse_recu (singlelist * head, singlelist ** newhead) {singlelist * PSL; // termination condition if (Head = NULL) | (Head-> next = NULL) {* newhead = head; return head;} PSL = reverse_recu (Head-> next, newhead ); psl-> next = head; head-> next = NULL; return head ;}
6. Determine whether a one-way linked list has a ring

Ideas:

Figure 3 one-way linked list with loops

Generally, we can think of a simple way to solve this problem. It may be to traverse the nodes one by one and record the addresses of the nodes, when traversing the next node, determine whether it is in the node set that has been traversed. If so, the linked list has a ring. The time complexity of this method is O (n2 ).

I found a more efficient method on the Internet. It is similar to the method in the previous 3rd question. It sets two traversal pointers. The first pointer firstptr takes two steps at a time, and the second pointer takes one step at a time, in this way, if the two pointers meet each other, the linked list has a ring.

Analysis shows that if the linked list has a ring, when the second pointer first reaches the entry node of the ring, the first pointer must already be on a node in the ring, the next two pointers rotate and traverse in the ring of the linked list. Because the first pointer takes one more step than the second one at a time, it will surely catch up with the second pointer.

I think there should be a strict proof that we can catch up here. Suppose there are n nodes in the ring, marked as 0 to n-1, 3, respectively, when the second pointer arrives at the entry node of the ring for the first time, the first pointer points to node A. If they encounter each other after I, that is, I % N = (a + 2 * I) */n indicates that the linked list has a ring.

Therefore, whether the two pointers can meet in the ring is converted into a positive integer I, So that I % N = (a + 2 * I) */n, where (n> = 2, A> = 0 and a <n. I have never proved this problem because I am not good at number theory. Please advise me here?

Use the code implementation method to confirm whether the linked list has a ring.

Code implementation:

// Determine whether a one-way linked list has a ring. // input parameter: Header pointer of a single-link table // output parameter: NONE // return value: true if a link exists, returns falsebool isloop (singlelist * head) {singlelist * firstptr, * secondptr; firstptr = head; secondptr = head; while (firstptr & firstptr-> next) {firstptr = firstptr-> next; secondptr = secondptr-> next; If (firstptr = secondptr) {return true ;}} return false ;}
7. Determine whether two one-way linked lists overlap

Ideas:

Figure 4 intersection one-way linked list

Consider that if two one-way linked lists intersect (4), the two linked lists certainly have a common node.

To solve this problem, the most common idea is to determine whether the node of a linked list exists in another linked list. This method needs to be implemented in a double loop, so the time complexity is O (n2 ).

We further study the characteristics of the intersection linked list and find that if the two linked lists overlap, the last node of the two linked lists must be the same. Therefore, you only need to judge whether the last node of the two linked lists is the same. This method only needs to traverse each linked list and find their final nodes.AlgorithmThe complexity is O (n ).

Code implementation:

// Determine whether two one-way linked lists are intersecting. // input parameter: the header pointer of the two single-chain tables. // output parameter: NONE // return value: true if the two single-chain lists are intersecting, returns falsebool isintersect (singlelist * head1, singlelist * head2) {singlelist * firstptr = head1, * secondptr = head2; If (firstptr = NULL) | (secondptr = NULL) {return false;} // cyclically traverse the first linked list and find the last element while (firstptr-> next) {firstptr = firstptr-> next;} // cyclically traverse the second linked list and find the last element while (secondptr-> next) {secondptr = secondptr-> next ;} if (firstptr = secondptr) {return true;} return false ;}

Extended question: is the first intersection of two linked lists returned?

After carefully reading the idea of the previous problem, you can find the first solution to the problem. However, the time complexity is O (n2 ). Can we improve the efficiency of the algorithm just like the second method? The answer is yes, of course.

By analyzing the properties of the two linked lists, we can see that if the two linked lists overlap, the linked list nodes after the intersection belong to the two linked lists at the same time. It can be inferred that the number of nodes on each linked list must be the same after the intersection. Therefore, if the number of two linked list nodes is len1 and len2 (len1> len2), then their first point on the first linked list must be the (len1-len2) nodes after each node.

To sum up the above analysis, we come up with an algorithm:

(1) traverse the two linked lists and obtain the number of nodes of the two linked lists, respectively, len1 and len2.

(2) Let the multi-node list first | len1-len2 |

(3) The two linked lists step backward at the same time and determine whether the nodes are the same. The first point of similarity is the first point of intersection.

Code implementation:

 // calculate the first intersection of two one-way linked lists. // input parameters: two single-chain table header pointers // output parameters: NONE // return value: intersection returns the first intersection pointer, not intersection returns nullsinglelist * firstintersectnode (singlelist * head1, singlelist * head2) {singlelist * firstptr = head1, * secondptr = head2; int len1 = 0, len2 = 0; // cyclically traverse the first linked list while (firstptr) {firstptr = firstptr-> next; len1 ++;} // cyclically traverse the second linked list while (secondptr) {secondptr = secondptr-> next; len2 ++;} firstptr = head1; secondptr = head2; // Let the pointer pointing to a longer-chain table first walk out of the long step if (len1> len2) {for (INT I = 0; I <(len1-len2); I ++) {firstptr = firstptr-> next ;}} else {for (INT I = 0; I <(len2-len1); I ++) {secondptr = secondptr-> next ;}} while (firstptr & secondptr) {If (firstptr = secondptr) {return firstptr;} firstptr = firstptr-> next; secondptr = secondptr-> next;} return NULL ;} 

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.