01/10/2018, 17:14

Lỗi insert phần tử trong danh sách liên kết

Em chào anh chị. Em đang học môn cấu trúc dữ liệu ở trường. Em có đoạn code sau mong anh chị giúp em. Chỗ int main(), lúc chạy chương trình, sau khi nhập p.tử X= và vị trí P = để thêm phần tử vào vị trí trong danh sách, thì sau khi nhập xong chương trình không xuất ra danh sách sau khi thêm. Mong anh chị sửa lỗi code giúp em. Chân thành cảm ơn.
http://codepad.org/iPZromvU

#include <stdio.h>
#include <conio.h>
#include <malloc.h>

typedef int ElementType;
struct Node{
	ElementType Element;
	Node *Next;
};
typedef Node *Position;
typedef Position List;

void MakeNull(List *Head)
{
	(*Head)=(Node*)malloc(sizeof(Node));
	(*Head)->Next = NULL;
}

Position First(List L)
{
	return L;
}
Position Next(Position P, List L)
{
	return P->Next;
}
ElementType Retrieve(Position P, List L)
{
	return P->Next->Element;
}
Position EndList(List L)
{
	Position P = First(L);
	while(P->Next != NULL)
	{
		return P=P->Next;
	}
	return P;
}
Position Locate(ElementType X, List L)
{
	Position P = L;
	int Found = 0;
	while(P->Next != NULL && Found == 0)
	{
		if(Retrieve(P,L) == X) Found = 1;
		else 
		P=P->Next;
	}
	return P;
}
void Insert(ElementType X, Position P, List *L)
{
	Position T = (Node*)malloc(sizeof(Node));
	T->Element = X;
	T->Next = P->Next;
	P->Next = T;
}
void Delete(Position P, List *L)
{
	Position T;
	if(P->Next != NULL)
	{
		T->Next = P->Next;
		P->Next = T->Next;
		free(L);
	}
	else
	{
		printf("
Loi ! Danh sach rong khong the xoa duoc ! ");
	}
}
void Input(List *L)
{
	int i,n,x;
	printf("Ban muon nhap bao nhieu phan tu trong danh sach: ");scanf("%d",&n);
	for(i=1; i<=n; i++)
	{
		printf("Phan tu thu %d: ",i);scanf("%d",&x);
		Insert(x,EndList(*L),L);
	}
}

void Output(List L)
{
	Position P = First(L);
	while(P->Next != NULL)
	{
		printf("%4d",Retrieve(P,L));
		P=P->Next;
	}
	printf("
");
}

int main()
{
	List L;
	ElementType X;
	Position P;
	MakeNull(&L);
	Input(&L);
	printf("	Danh sach sau khi nhap:	");
	Output(L);
	
	//them phan tu X vao vi tri P trong danh sach
	printf("
Nhap phan tu can them: X=  ");scanf("%d",&X);
	printf("
Nhap vi tri can them: P=  ");scanf("%d",&P);
	Insert(X,P,&L);
	printf("
Danh sach sau khi them: ");
	Output(L);
	
	
	getch();
	return 0;
}
Bài liên quan
0