1. Find the K-th element of the linked list.
2 It is known that the two linked lists head1 and head2 are ordered separately. Please combine them into a linked list and they are still ordered.
(Keep all nodes, even if the size is the same)
Here two methods are used: recursive and non-recursive.
Typedef struct node
{
Int data;
// Linknode * next; Incorrect !!!
Struct node * next;
} Linknode;
Linknode * createLink (int n );
========================================================== ========================================================== ======
1. Find the K-th element of the linked list.
Code implementation:
// Define node1 and node2 nodes to compare different k-1), when node2 to the last node, node1 is the request.
Bool findLastKnode (Linknode * head, int numK)
{
Assert (head! = NULL );
Linknode * node1, * node2;
Node1 = head;
Node2 = head;
Int num = 1;
// 1 locate node2
While (node2! = NULL & num <numK)
{
Num ++;
Node2 = node2-> next;
}
// Todo: Do I need to improve this judgment condition ???
If (num = numK & node2! = NULL) // search successful
{
// While (node2! = NULL)
While (node2-> next! = NULL)
{
Node1 = node1-> next;
Node2 = node2-> next;
}
Cout <"the node found is:" <node1-> data <endl;
Return true;
}
Cout <"I'm sorry, can not find it." <endl;
Return false; // search failed
}
Test code:
Int num;
Cout <"Enter the number of nodes to be created n :";
Cin> num;
Linknode * link;
Link = createLink (num );
Bool isFind = findLastKnode (link, 2 );
Return 0;
2 We know that the two linked lists head1 and head2 are ordered separately. Please combine them into a linked list.
(Keep all nodes, even if the size is the same)
Note: The code below assumes that head1 and head2 are sorted in order.
2.1 Non-Recursive Method
Linknode * MergeLink (Linknode * head1, Linknode * head2) {if (head1 = NULL) return head2; if (head2 = NULL) return head1; Linknode * head, * curnode; // The header and ID node of the created linked list. Linknode * link1, * link2; link1 = head1; link2 = head2; // 1 determine the header node if (link1-> data <= link2-> data) {head = link1; link1 = link1-> next;} else {head = link2; link1 = link2-> next ;} cout <"the first element is"
2. Recursive Method
Linknode * MergeRecursion (Linknode * head1, Linknode * head2) {// 1 the final exit condition 2 recursion: narrowing down the range or scale if (head1 = NULL) return head2; if (head2 = NULL) return head1; Linknode * head; // the header and ID node of the created linked list. If (head1-> data <= head2-> data) {head = head1; head-> next = MergeRecursion (head1-> next, head2);} else {head = head2; head-> next = MergeRecursion (head1, head2-> next);} printLink (head); return head ;}
3 code Test
Int main () {int num1, num2; cout <"Enter the number of first and second linked lists:"; cin> num1> num2; Linknode * link1, * link2, * link; link1 = createLink (num1); link2 = createLink (num2); // link = MergeLink (link1, link2); link = MergeRecursion (link1, link2 ); return 0 ;}