Microsoft and other data structures and algorithms interview 100 questions 13th questions

Source: Internet
Author: User

13th questions
Question: enter a one-way linked list and output the k-th node in the list.

This question is relatively simple, is for this linked list, define two pointers head1 head2, and then let head1 forward a K-1 position after head2 and head1 move forward at the same time, know head1 know NULL pointer, head2 is the k pointer to the bottom.

Code:
[Cpp]
# Include <iostream>
Using namespace std;
 
 
Typedef struct node
{
Node * nodeNext;
Int value;
} Node;
 
Int seekReListK (node * head, int k)
{
If (NULL = head)
{
Cout <"Empty linked list ";
Return-1;
}
Node * head1 = head;
Node * head2 = head;
K = k-1;
While (k)
{
K = k-1;
If (NULL! = Head1-> nodeNext)
Head1 = head1-> nodeNext;
Else
{
Cout <"K exceeds the length of the linked list" <endl;
Return-1;
}
}
// Head1 is k faster than head2
While (NULL! = Head1-> nodeNext)
{
Head1 = head1-> nodeNext;
Head2 = head2-> nodeNext;
}

Return head2-> value;
}
Int main ()
{
// Create a linked list
Node * a = new struct node ();
Node * B = new struct node ();
Node * c = new struct node ();
Node * d = new struct node ();
Node * e = new struct node ();
Node * f = new struct node ();
Node * g = new struct node ();
Node * h = new struct node ();
Node * I = new struct node ();
Node * j = new struct node ();
A-> nodeNext = B;
B-> nodeNext = c;
C-> nodeNext = d;
D-> nodeNext = e;
E-> nodeNext = f;
F-> nodeNext = g;
G-> nodeNext = h;
H-> nodeNext = I;
I-> nodeNext = j;
J-> nodeNext = NULL;
A-> value = 0;
B-> value = 1;
C-> value = 2;
D-> value = 3;
E-> value = 4;
F-> value = 5;
G-> value = 6;
H-> value = 7;
I-> value = 8;
J-> value = 9;
 
Cout <seekReListK (a, 1) <endl;
Cout <seekReListK (a, 10) <endl;
Cout <seekReListK (a, 11) <endl;
Return 0;
}

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.