#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;
}