Traverse the Linked List
Time limit: 5000ms
Memory limit: 256mb
Description:
In this exercise, you are required to implement the following two functions on a linked list.
1. Judge whether the linked list contains a certain value.
2. Print all integers stored in the linked list.
The program firstly reads an integer n which is the initial number of integers in the linked list, and then reads the n integers and inserts them into the linked list p.
After that it reads an integer m, representing the number of judging operations. Then it reads m integers and check whether each of them exists in the linked list one by one. Finally, print all integers from the head of linked list.
Your task is to complete the following functions.
bool Exist(List p, int value);
Return 1 if linked list p contains the value, otherwise return 0.
void Print(List p);
Print all integers from the head of linked list.
Sample Input:
5
4 2 3 10 7
3
1 4 2
Sample Output:
1 does not exist in the linked list.
4 exists in the linked list.
2 exists in the linked list.
7 10 3 2 4
Code Template:
#include <stdio.h>
#include <stdlib.h>
typedef struct linked_list_node{
int value;
struct linked_list_node* next;
} Node;
typedef Node* List;
List Insert(List p, int value)
{
List ptr = (List)malloc(sizeof(Node)); // allocate a piece of memory for the new head node
ptr->value = value;
ptr->next = p; // point to the original head node p
return ptr; // return address of the new head node
}
int Exist(List p, int value)
{
// judge whether linked list p contains the value
// you should visit each node of the linked list one by one, and check whether it is equal to the value
// if you find it then return 1, otherwise return 0
while(p!=NULL)
{
}
return 0;
}
void Print(List p)
{
// print all integers from the head of linked list in one line(separated by a space), in other words, you should firstly print the integer p points to
// to be more specific, print p->value and then move p to the next node p->next recursively, until p points to NULL
}
int main()
{
List p = NULL;
int n, m;
int value;
scanf("%d", &n);
for(int i=0; i<n; i++)
{
int value;
scanf("%d", &value);
p = Insert(p, value);
}
scanf("%d", &m);
for(int i=0; i<m; i++)
{
scanf("%d", &value);
if(Exist(p, value)==1) printf("%d exists in the linked list.\n", value);
else printf("%d does not exist in the linked list.\n", value);
}
Print(p);
return 0;
}
Submit