数据结构双链表之(一)初始化&&尾插&&显示表

本文介绍了双链表的初始化、尾插及显示表的基本操作。通过DList.h、DList.cpp和main.cpp三个文件展示了双链表的C++实现,包括创建新节点、尾部插入元素以及显示链表内容的功能。提供了用户交互界面,允许进行插入数据、显示链表等操作。
摘要由CSDN通过智能技术生成

1. 思路

1.1 初始化

在这里插入图片描述
与单链表的区别在于:双链表节点中有一个前向节点。

1.2 尾插

在这里插入图片描述在这里插入图片描述

1.3 显示表

在这里插入图片描述

2. 代码

2.1 DList.h

#ifndef _DList_H_
#define _DList_H_

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

typedef int ElemType;

typedef struct Node
{
	ElemType data;
	struct Node *next;
	struct Node *prio;
}Node, *pNode;

typedef struct List
{
	pNode first;
	pNode last;
	int   size;
}List;

//初始化双链表
void InitDList(List *list);

//显示表
void show(List *list);

//尾插
void push_back(List *list, ElemType x);

#endif //_DList_H_

2.2 DList.cpp

#include "DList.h"

void InitDList(List *list)
{
	Node *s = (Node *)malloc(sizeof(Node));
	assert(s != NULL);
	list->first = list->last = s;
	list->last->next = NULL;
	list->first->prio = NULL;
	list->size = 0;	
}

Node* buynode(ElemType x)
{
	Node *s = (Node *)malloc(sizeof(Node));
	assert(s != NULL);
	s->data  = x;
	s->prio  = NULL;
	s->next  = NULL;
	return s;
}

void push_back(List *list, ElemType x)
{
	Node *s = buynode(x);
	s->prio = list->last;
	list->last->next = s;
	
	list->last = s;
	list->size++;
}

void show(List *list)
{
	Node *s = list->first->next;
	while(s != NULL)
	{
		printf("%d<->", s->data);
		s = s->next; 
	}
	printf("NULL\n");
}

2.3 main.cpp

#include "DList.h"

int main()
{
	List mylist;
	InitDList(&mylist);
	
	ElemType Item;
	int select = 1;
	while(select)
	{
		printf("*********************************\n");
		printf("* [1] push_back  [2] push_front *\n");
		printf("* [3] show_list  [4] pop_back   *\n");
		printf("* [5] pop_front  [6] insert_val *\n");
		printf("* [7] find       [8] length     *\n");
		printf("* [9] delete_val [10] sort      *\n");
		printf("* [11] resver    [12] clear     *\n");
		printf("* [13] destroy   [0] quit       *\n");
		printf("*********************************\n");
		printf("请选择:>");
		scanf("%d", &select);
		
		switch(select)
		{
			case 1:
				printf("请输入要插入的数据(-1结束):");
				while(scanf("%d",&Item), Item != -1)
				{
					push_back(&mylist, Item);
			       	}
				break;			
			case 2:			
				//printf("请输入要插入的数据(-1结束):");
				//while(scanf("%d",&Item), Item != -1)
				//{
				//	push_front(&mylist, Item);
				//}
				break;
			case 3:
				show(&mylist);
				break;
			case 4:
				//pop_back(&mylist);
				break;
			case 5:
 				//pop_front(&mylist);
				break;
			default:
				break;
		}
	}
	return 0;
}

3. 结果

在这里插入图片描述

总结

继续干。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值