今天我们要讨论的是单链表的创建插入与删除
/*注意因为建表时用了字符型数据所以输入数字时只能输0~9*/
#include<stdio.h>
#include<stdlib.h>
typedef struct node //结点的结构体
{
int data; //数据域
struct node *next; //指针域
}node, *list;
list HeadCreat(); //头插法创建链表
list TailCreat(); //尾插法创建链表
void Insert(list head, int x, char value, int length);//向链表中特定位置插入一个元素
void Delete(list head, int x, int length); //删除一个结点
int Length(listhead); //统计链表的长度
void print(head); //输出链表
int main(void)
{
list head;
int x, length;
char value;
// head = HeadCreat(); //头插法创建链表
head = TailCreat(); //尾插法创建链表
length = Length(head);
print(head);
printf("\n");
printf("请输入要插入的数值:");
scanf("%c",&value);
printf("%c\n",value);
printf("请输入要插入的位置:");
scanf("%d",&x);
printf("%d\n",x);
Insert(head, x, value, length); //向链表中特定位置插入一个元素
print(head);
printf("\n");
printf("请输入要删除的结点:");
scanf("%d",&x);
Delete(head, x, length); //删除一个结点
print(head);
return 0;
}
list HeadCreat() //头插法创建链表
{
list head;
char c;
int flag = 1;
head = (list)malloc(sizeof(node)); //头结点,里面没有数据
if(!head)
printf("链表创建错误!");
head->next = NULL;
while(flag == 1)
{
printf("请输入数据:");
c = getchar();
flushall(); //清除enter所产生的缓存数据
if(c != '$')
{
node *w;
w = (node *)malloc(sizeof(node));
w->data = c;
w->next = head->next;
head->next = w;
}
else
flag = 0;
}
return head;
}
list TailCreat() //尾插法创建链表
{
list head;
node *p;
char c;
int flag = 1;
head = (list)malloc(sizeof(node)); //头结点,里面没有数据
if(!head)
printf("链表创建错误!");
p = head;
p->next = NULL;
head->next = NULL;
while(flag == 1)
{
printf("请输入数据:");
c = getchar();
flushall(); //清除enter所产生的缓存数据
if(c != '$')
{
node *w;
w = (node *)malloc(sizeof(node));
w->data = c;
p->next = w;
p = w;
}
else
flag = 0;
p->next = NULL;
}
return head;
}
int Length(list head) //统计链表的长度
{
node *p;
int i = 0;
p = head->next;
while(p)
{
p = p->next;
i++;
}
return i;
}
void Insert(list head, int x, char value, int length)//向链表中特定位置插入一个元素
{
node *pre, *p; //*pre为要插入位置的前驱结点
int i = 1;
pre = head;
p = (node *)malloc(sizeof(node));
while(i < x)
{
pre = pre->next;
i++;
}
if(i > length)
{
printf("插入错误!\n");
}
else
{
p->data = value;
p->next = pre->next;
pre->next = p;
}
}
void Delete(list head, int x, int length) //删除一个结点
{
node *pre, *p; //*per为要删除结点的前驱结点,*hid为要删除的结点
int i = 1;
p = head;
if(x > length)
printf("输入结点位置错误!\n");
else
{
while(i <= x)
{
pre = p;
p = p->next;
i++;
}
pre->next = p->next;
}
}
void print(list head) //输出链表
{
node *p;
p = head->next;
for(; p != NULL; p = p->next)
printf("%c ",p->data);
}
单链表的创建插入与删除
| 评论 |
|
|
