Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Exercise 72

C Exercise 72

100 Classic C Language Examples 100 Classic C Language Examples

**Problem:** Create a linked list.

**Analysis:** None.

Example

// Created by www.runoob.com on 15/11/9.

// Copyright (c) 2015 Runoob Tutorial. All rights reserved.

//

#include

<

stdio.h

#include

<

stdlib.h

#include

<

malloc.h

typedef

struct

LNode

{

int

data

;

struct

LNode

next

;

}

LNode

,*

LinkList

;

LinkList

CreateList

(

int

n

)

;

void

print

(

LinkList

h

)

;

int

main

(

)

{

LinkList

Head

=

NULL

;

int

n

;

scanf

(

"

%d

"

,&

n

)

;

Head

=

CreateList

(

n

)

;

printf

(

"

The values of the newly created linked list elements are:

\

n

"

)

;

print

(

Head

)

;

printf

(

"

\

n

\

n

"

)

;

system

(

"

pause

"

)

;

return

0

;

}

LinkList

CreateList

(

int

n

)

{

LinkList

L

,

p

,

q

;

int

i

;

L

=

(

LNode

)

malloc

(

sizeof

(

LNode

)

)

;

if

(

!

L

)

return

0

;

L

->

next

=

NULL

;

q

=

L

;

for

(

i

=

1

;

i

<=

n

;

i

++

)

{

p

=

(

LinkList

)

malloc

(

sizeof

(

LNode

)

)

;

printf

(

"

Please enter the value of the %d-th element:

"

,

i

)

;

scanf

(

"

%d

"

,&

(

p

->

data

)

)

;

p

->

next

=

NULL

;

q

->

next

=

p

;

q

=

p

;

}

return

L

;

}

void

print

(

LinkList

h

)

{

LinkList

p

=

h

->

next

;

while

(

p

!=

NULL

)

{

printf

(

"

%d

"

,

p

->

data

)

;

p

=

p

->

next

;

}

}

100 Classic C Language Examples 100 Classic C Language Examples