Code:
#include "conio.h"
#include "stdio.h"
#include "alloc.h"
typedef unsigned int Position;
typedef int ElementType;
typedef struct Node {
ElementType Element;
Node *Next;
};
typedef Node *List;
//khoi tao danh sach rong
List MakeNull_List(){
List Header = (List)malloc(sizeof(List));
(Header)->Next = NULL;
return Header;
}
//kiem tra danh sach rong
char Empty_List(List L) {
return L->Next == NULL;
}
//Khoi tao 1 node
Node *Make_Node(ElementType X) {
Node *temp = (Node*)malloc(sizeof(Node));
temp->Element = X;
temp->Next = NULL;
return temp;
}
//xen mot phan tu vao danh sach
void Insert_List(ElementType X, List P) {
Node *Temp = Make_Node(X);
Temp->Next = P->Next;
P->Next = Temp;
}
// Chen 1 phan tu vao vi tri i trong danh sach
void Insert_List(List L, ElementType x, Position i) {
List temp = L;
Position j = 1;
while(j<i && temp!=NULL) {
temp = temp->Next;
j++;
}
if(i==j)
Insert_List(x,temp);
else
printf("\n\tVi tri chen khong dung.");
}
//nhap dach sach co n phan tu
List Input_List(int n) {
List L = MakeNull_List();
ElementType x;
for(int i = 1; i<=n; i++) {
printf("\tElement %d = ",i);
scanf("%d",&x);
Insert_List(x,L);
}
return L;
}
void Out_List(List L) {
List temp = L;
while(!Empty_List(temp)) {
printf("%d\t",temp->Next->Element);
temp = temp->Next;
}
}
//the main programming
void main() {
clrscr();
ElementType x;
int n,i;
printf("Nhap so phan tu n = ");
scanf("%d",&n);
List L = Input_List(n);
printf("Danh sach vua nhap:\n");
Out_List(L);
printf("\nNhap vi tri can chen:");
scanf("%d",&i);
printf("Nhap gia tri can chen:");
scanf("%d",&x);
Insert_List(L,x,i);
printf("\nDanh sach vua chen phan tu moi:\n");
Out_List(L);
getch();
}