线性表的单链表的定义、初始化等操作

#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERR 0
#define MAXSIZE 100
typedef int ElemType;

//定义
typedef struct Node
{
	ElemType data;
	struct Node *next;
}Node,*LinkedList;

//初始化
LinkedList LinkedListInit()
{
	Node *L;
	L = (Node * )malloc(sizeof(Node));
	if (L==NULL)
	{
		printf("申请内存空间失败.");
	}
	L->next=NULL;
	return L; 
}

//单链表的建立1,头插入法建立单链表
LinkedList LinkedListCreateHead()
{
	Node *Head;
	Head = (Node *)malloc(sizeof(Node));//申请头节点空间
	Head->next=NULL;
	ElemType x;//x为链表数据域中的数据
	while (scanf("%d",&x)!=EOF)
	{
		Node *P;
		P=(Node *)malloc(sizeof(Node));
		
		P->data=x;

		P->next=Head->next;
		
		Head->next=P;
	
	}
	return Head;
}

//单链表的建立2,尾插入法建立单链表
LinkedList LinkedListCreateTail()
{
	//申请头节点
	Node *Head;
	Head = (Node*)malloc(sizeof(Node));
	Head->next=NULL;

	//定义Tail始终指向终端结点,开始时指向头结点 
	Node *Tail;
	Tail=Head;

	ElemType x;
	while (scanf("%d",&x)!=EOF)
	{
		Node *P = (Node *)malloc(sizeof(Node));//申请新的结点
		
		P->data=x;
		Tail->next=P;
		Tail=P;
	}
	Tail->next=NULL;
	return Head;
	
}
//单链表的插入,在链表的第i个位置插入x的元素
LinkedList LinkedListInsert(LinkedList L,int i,ElemType x)
{
	Node *pre;
	pre = L;
	int temp=0;
	for (temp=1;temp<i;temp++)
		pre=pre->next;
	Node *P = (Node *)malloc(sizeof(Node));
	P->data = x;
	P->next=pre->next;
	pre->next=P;
	return L;

}

//单链表的删除,在链表中删除值为x的元素

LinkedList LinkedListDel(LinkedList L,ElemType x)
{
	Node *pre,*p;//p为查找的结点 pre为前驱结点
	p=L->next;
	while (p->data!=x)
	{
		pre=p;
		p=p->next;
		
	}
	pre->next=p->next;
	free(p);
	return L;
	
}
//显示单链表数据
void LinkedListShow(LinkedList L)
{
	LinkedList temp;
	int i=0;
	for(i=1,temp = L->next; temp != NULL; i++,temp = temp->next)
        printf("(%d)->%d ",i,temp->data);
    printf("\n");
}
int main()
{

	//键盘中输入EOF方法:press Ctrl+Z on a new line
	LinkedList L;
	//尾插法建表
	printf("请输入单链表的数据:\n");
	L=LinkedListCreateTail();
	printf("该链表为:\n");
	LinkedListShow(L);

	int i;
	ElemType x;
	printf("请输入插入数据的位置和值,用空格隔开:\n");
	scanf("%d %d",&i,&x);
	LinkedListInsert(L,i,x);
	printf("该链表为:\n");
	LinkedListShow(L);

	printf("请输入要删除的元素的值:");
    scanf("%d",&x);
    LinkedListDel(L,x); 
	printf("该链表为:\n");
	LinkedListShow(L);
	
	return 0;
}

  

posted @ 2015-09-22 23:13  浩月白雪  阅读(5471)  评论(0编辑  收藏  举报