您的位置:首页 > 其它

链表存储基本操作

2016-12-01 22:39 288 查看
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
/*定义表示结点的结构体类型*/
typedef struct list
{
int data;
struct list* next;
}LIST;
void add(int data);
LIST* findBack();
void insertBack(LIST *p);
void insert(int position,int data);
void discs(int data);
void returnvalue();
void del(int position);
void change(int position,int data);
void showMenu();

LIST head; //头结点
char ch;
int count=0; //统计数据个数
int position; //位置
int main()
{
int select;
head.next=NULL; //将头结点的next置为NULL
while(1)
{
showMenu();
printf("请选择需要的操作:");
scanf("%d",&select);
fflush(stdin);  //清除键盘缓冲区
switch(select)  //根据用户选择,调用相应函数完成
{
case 1:
case 2:
case 3:
case 4:
case 0:exit(1);
default:printf("输入错误!\n");
}
system("pause");
}
return 0;
}
///////////     函数的定义       //////////
void add(int data) //添加
{
LIST *p;
p=(LIST *)malloc(sizeof(LIST)); //新建结点
count++;
if(p == NULL)
{
printf("动态内存分配失败!");
return;
}
p->data = data;
insertBack(p);
}

LIST* findBack() //查找尾结点地址
{
LIST *p;
p=&head;
while(p->next!=NULL)
{
p=p->next;
}
return p;
}

void insertBack(LIST *p) //插入一个结点
{
LIST *tail;
tail = find
c8b4
Back();
tail->next = p;
p->next = NULL;
return ;
}

void change(int position,int data)  //改变
{
LIST *p;
p=&head;
while(position)
{
p = p->next;
position--;
}
p->data = data;
}

void insert(int position,int data)  //插入
{
LIST *p,*pre;
p=(LIST *)malloc(sizeof(LIST));
if(position>(count+1))
{
printf("超出插入位置范围!\n");
system("pause");
return;
}
pre=&head;  //pre指向头结点
position--;
while(position)
{
if(p!=NULL)
{
position--;
pre = pre->next; //pre指向下一个结点
}
}
if(p!=NULL)
{
p->next = pre->next;
pre->next = p;
p->data = data;
}
}
void del(int position) //删除
{
LIST *p,*pre;
pre=&head;  //pre指向头结点
p=head.next; //p指向第一个结点
if(position < 0||position > count)
{
printf("你删除的位置不存在\n");
system("pause");
return;
}
position--;
while(position)
{
position--;
pre = pre->next; //p pre指向下一个结点 pre在p之前
p = p->next;
}
if(p!=NULL)
{
pre->next = p->next;
free(p);
}
}
void returnvalue()  //反转
{
LIST *p,*q,*headp;
headp=&head;
p=&head;
p = p->next;
while(p->next != NULL)
{
q = p->next;
p->next = q->next;
q->next = headp->next;
headp->next = q;
}
p->next =headp;
headp =p->next;
p->next = NULL;
printf("反转成功!\n");
system("pause");
}
void showMenu()
{
system("cls");  /*清屏*/
return;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐