1.4双向链表表示与实现

1.4双向链表表示与实现

1、双向链表是指链表中每个结点都有两个指针域,一个指向后继结点,一个指向前驱结点。prior和next.

2、双向链表也分带头和不带头,带头操作更加方便。双向链表也有循环结构,称双向循环链表。

3、带头双向循环链表的判空条件为head->prior==head或head->next==head;

代码实现:

DLinkList.h

#pragma once
#include <stdio.h>
#include <stdlib.h>

typedef int DataType;

typedef struct Node
{
	DataType data;
	struct Node* prior, * next;   //p为前指针,q为后指针
}DListNode,*DListLink;


//插入函数
int InsertDList(DListLink head,int i,DataType e)
{
	DListNode* p, * s;
	int j=0;
	p = head->next;
	while (p!=head && j<i)
	{
		p = p->next;
		j++;
	}
	if (j!=i)
	{
		printf("插入位置不正确");
		return 0;
	}
	s = (DListNode *)malloc(sizeof(DListNode));
	if (s==NULL)
	{
		return -1;
	}
	s->data = e;
	s->prior = p->prior;
	p->prior->next = s;
	s->next = p;
	p->prior = s;
	return 1;
}

//删除函数
int DeleteDList(DListLink head, int i, DataType *e)
{
	DListNode* p, * s;
	int j = 0;
	p = head->next;
	while (p != head && j < i)
	{
		p = p->next;
		j++;
	}
	if (j != i)
	{
		printf("输入位置不正确");
		return 0;
	}
	p->prior->next = p->next;
	p->next->prior = p->prior;
	free(p);
	return 1;
}

//初始化函数
int InitDList(DListLink *head)
{
	*head = (DListLink)malloc(sizeof(DListNode));
	if (!head)
		return -1;
	(*head)->next = *head;
	(*head)->prior = *head;
	return 1;
}

//创建循环单链表
int CreateDList(DListLink head,int n)
{
	DListNode* s, * q;
	DataType e;
	q = head;
	for (int i = 1; i <= n; i++)
	{
		printf("请输入第%d个元素:",i);
		e = getchar();
		s = (DListNode *)malloc(sizeof(DListNode));
		s->data = e;
		s->next = q->next;
		q->next = s;
		s->prior = q;
		head->prior = s;
		q = s;
		getchar();
	}
	return 1;
}

//输出函数
void PrintDList(DListLink head)
{
	DListNode* p;
	p = head->next;
	while (p!=head)
	{
		printf("%c",p->data);
		p = p->next;
	}
	printf("\n");
}

test.c

#include <stdio.h>
#include <stdlib.h>
#include "DLinkList.h"

void main()
{
	DListLink h;
	int n;
	int pos;
	char e;
	InitDList(&h);
	printf("输入元素的个数:");
	scanf_s("%d",&n);
	getchar();
	CreateDList(h, n);
	printf("链表中的元素:");
	PrintDList(h);
	printf("请输入插入的元素:");
	scanf_s("%c",&e);
	getchar();
	printf("请输入插入元素的位置:");
	scanf_s("%d", &pos);
	InsertDList(h, pos, e);
	printf("插入后链表中的元素:");
	PrintDList(h);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值