当前位置:首页 » 编程语言 » 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);//第二题输出结果
}

热点内容
sql日志压缩 发布:2025-07-12 12:39:53 浏览:343
红点角标算法 发布:2025-07-12 12:11:16 浏览:844
开心消消乐服务器繁忙什么情况 发布:2025-07-12 12:11:14 浏览:239
数据库的封锁协议 发布:2025-07-12 12:10:35 浏览:725
如何配置一台长久耐用的电脑 发布:2025-07-12 11:43:03 浏览:602
昆明桃源码头 发布:2025-07-12 11:38:45 浏览:569
大司马脚本挂机 发布:2025-07-12 11:38:35 浏览:459
数据库实时监控 发布:2025-07-12 11:31:33 浏览:744
vb6反编译精灵 发布:2025-07-12 11:23:12 浏览:998
模拟存储示波器 发布:2025-07-12 11:10:58 浏览:814