当前位置:首页 » 编程语言 » c语言双向链表的建立

c语言双向链表的建立

发布时间: 2023-08-13 13:07:50

A. 使用c语言实现双向链表的建立、删除和插入

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
struct list{
int data;
struct list *next;
struct list *pre;
};
typedef struct list node;
typedef node *link;
link front=NULL,rear,ptr,head=NULL;

link push(int item){
link newnode=(link)malloc(sizeof(node));
newnode->data=item;
if(head==NULL)
{
head=newnode;
head->next=NULL;
head->pre=NULL;
rear=head;
}
else
{
rear->next=newnode;
newnode->pre=rear;
newnode->next=NULL;
rear=newnode;
}
return head;
}

void makenull(){
front=NULL;
rear=NULL;
}

empty(){
if(front==NULL)
return 1;
else
return 0;
}

int tops(){
if(empty())
return NULL;
else
return rear->data;
}

void pop(){
if(empty())
printf("stack is empty!\n");
else
rear=rear->pre;
}

void display(link l){
link p;
p=l;
while(p!=NULL){
printf("%d->",p->data);
p=p->next;
}
}

void main(){
int n,i;
printf("input your first data!\n");
scanf("%d",&n);
front=push(n);
/*another data*/
for(i=0;i<3;i++)
{
printf("input:\n");
scanf("%d",&n);
push(n);
}
ptr=front;
display(ptr);
printf("\n Please enter any key to pop");
pop();
ptr=front;
display(ptr);

}

B. c语言数据结构(双向链表排序)

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

#define ElemType int

int count=0;

typedef struct DulNode
{
ElemType data;
DulNode *prior;
DulNode *next;
}DulNode,*DulLinkList;

//初始化链表,结束后产生一个头结点指针
void InitDLList(DulLinkList *L)
{
(*L)=(DulLinkList)malloc(sizeof(DulNode));
(*L)->next=*L;
(*L)->prior=(*L)->next;
}
//对链表进行插入操作
void ListInsert(DulLinkList *L)
{
int i=0,n;
ElemType temp;
DulNode *s,*p;
p=(*L)->next;
printf("请输入插入元素数量:\n");
scanf("%d",&n);
count=n;
printf("请输入%d个自然数\n",n);
while(i<n)
{
scanf("%d",&temp);
s=(DulNode*)malloc(sizeof(DulNode));
s->data=temp;
while((p!=(*L))&&(p->data<temp))//查找所要插入的位置
{
p=p->next;
}

s->prior=p->prior;//新节点的插入
s->next=p;
p->prior->next=s;
p->prior=s;

p=(*L)->next;//将指针回指到链表第一个非空节点,主要是为了下次查找插入位置
i++;
}
}
void Display(DulLinkList L)
{
DulNode *p;
p=L->next;
printf("双向链表中的数据为:\n");
while(p!=L)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
void Sort(DulLinkList *L)
{
ElemType temp;
DulNode *p,*q;
p=(*L)->next;
q=(*L)->prior;
if(count%2!=0)
q=q->prior;
p=p->next;

while(p!=q)
{
temp=p->data;
p->data=q->data;
q->data=temp;

p=p->next;

if(p!=q) //第二题只需交换节点数据
q=q->prior;//这几个if else语句需要仔细
else
break;
if(p!=q)
p=p->next;
else
break;
if(p!=q)
q=q->prior;
else
break;
}

}
void main()
{
DulLinkList L;
InitDLList(&L);//初始化链表
ListInsert(&L);//顺序插入数据
Display(L);//显示结果
Sort(&L);//第二题操作
Display(L);//第二题输出结果
}

热点内容
c语言取随机数 发布:2025-02-06 02:46:57 浏览:863
uc缓存的视频卡住 发布:2025-02-06 02:17:05 浏览:144
解压同学介绍 发布:2025-02-06 02:13:10 浏览:776
icsftp 发布:2025-02-06 02:12:59 浏览:325
ftp跨域上传文件 发布:2025-02-06 02:09:22 浏览:822
非递归全排列算法 发布:2025-02-06 02:06:45 浏览:551
vs反编译dll 发布:2025-02-06 02:06:00 浏览:584
ubuntu设置ftp权限 发布:2025-02-06 01:54:07 浏览:599
奇瑞5哪个配置值得买 发布:2025-02-06 01:51:56 浏览:552
黑鲨手机哪里看安卓版本 发布:2025-02-06 01:36:04 浏览:803