Data Structure - Circular Singly Linked List

describe

 

Create a circular linked list, and start from any node, traverse the entire linked list. 

Part of the code has been given, please complete it. Please do not include the given code when submitting.

 

void Destroy(Node* head)
{
    Node * p;
    while(head->next!=head)
    {
        p = head->next;
        head->next = p->next;
        free(p);
    }
    free(head);
}

intmain()
{
    int n, x;
    scanf("%d", &n);
    Node *head = CreateLinkList(n);
    while(scanf("%d", &x)!=EOF)
    {
        PrintLinkList(head, x);
    }
    Destroy(head);
    return 0;
}

enter

 

The first line of the input data is a positive integer n, and the second line is n integers, which are the element values ​​of the linked list node, and all the element values ​​are different. Next several lines, each line is an integer x, which is the value of any element in the linked list, input until the end of the file.

 

output

 

Starting from the node whose element value is x, traverse all nodes and output, with the element values ​​separated by spaces.

 

sample input

5
1 2 3 4 5
2
3
5
4

Sample output

2 3 4 5 1
3 4 5 1 2
5 1 2 3 4
4 5 1 2 3

Code test:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

typedef struct Node{
    int data;
    struct Node* next;
}Node;

Node* CreateLinkList(int n){
    Node *head,*p,*q;
    head=(Node*)malloc(sizeof(Node));
    int m;
    scanf("%d",&m);
    head->data=m;
    p=head;
    int i;
    for(i=1;i<n;i++){
        q=(Node*)malloc(sizeof(Node));
        scanf("%d",&m);
        q->data=m;
        p->next=q;
        p=p->next;
    }
    p->next=head;
    return head;
}

Node* PrintLinkList(Node *head,int x){
    Node * p;
    p=head;
    while(p->data!=x){
        p=p->next;
    }
    printf("%d",x);
    p=p->next;
    while(p->data!=x){
        printf(" %d",p->data);
        p=p->next;
    }
    printf("\n");
}

void Destroy(Node* head)
{
    Node *p;
    while(head->next!=head)
    {
        p = head->next;
        head->next = p->next;
        free(p);
    }
    free(head);
}

intmain ()
{
    int n, x;
    scanf("%d", &n);
    Node *head = CreateLinkList(n);
    while(scanf("%d", &x)!=EOF)
    {
        PrintLinkList(head, x);
    }
    Destroy(head);
    return 0;
}
View Code

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324686989&siteId=291194637