数据结构——练习之双向链表实现

数据结构——练习之双向链表实现

          为了掌握并使用双向链表,就动手写了这个小程序,包括一些双向链表的基本操作以及求集合并

源码:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
/**双向链表**/
typedef struct{
	int number;
}Node;
typedef struct NodeList{
	Node n;	//数据
	NodeList* prior;	//指向前驱元素
	NodeList* next;		//指向后继元素
	int length;
};
/**初始化**/
NodeList* InitList(){
	NodeList *h = (NodeList*)malloc(sizeof(NodeList));
	h->next = h;
	h->prior = h;
	h->length = 0;
	return h;
}
/**创建链表**/
void CreateList(NodeList* L){
	int n;
	printf("Input the number of the set: ");
	scanf("%d",&n);
	NodeList *p = L,*pre;
	Node node;
	for(int i = 0;i<n;i++){
		printf("Input the %d number:",i+1);
		scanf("%d",&node.number);
		pre = (NodeList*)malloc(sizeof(NodeList));
		pre->n = node;
		p->next = pre;
		pre ->prior = p;
		pre ->next = L;
		p = pre;
		L->prior = pre;
		L->length++;
	}
}
/**打印链表**/
void PrintList(NodeList *L){
	NodeList *p = L;
	int len = L->length;
	printf("The set is :\n");
	for(int i = 0;i<len;i++){
		p = p->next;
		printf("%d  ",(p->n.number));
	}
	printf("\n");
}
/**插入新元素**/
void InsertList(NodeList *L,int i,Node n){
	int len = L->length;
	NodeList *pre = L;
	int j = 0;
	if(i<0||i>len){
		printf("Error!Wrong position to insert!");
		exit(0);
	}else{
		while(j<i){
			pre = pre->next;
			j++;
		}
		NodeList* p = (NodeList*)malloc(sizeof(NodeList));
		p->n = n;
		p->next = pre->next;
		pre->prior = p;
		p->prior = pre;
		pre->next = p;
		L->length++;
	}
}
/**删除元素**/
void DelteList(NodeList *L,int i){
	int len = L->length;
	NodeList *pre = L;
	int j = 0;
	if(i<0||i>len){
		printf("Error!Wrong position to insert!");
		exit(0);
	}else{
		while(j<i){
			pre = pre->next;
			j++;
		}
		pre->next = pre->next->next;
		pre->next->next->prior = pre;
		L->length--;
	}
}
NodeList* MergeList(NodeList* A,NodeList* B){
	NodeList* a = A->next;
	NodeList* b;
	Node an,bn;
	int m = A->length;
	int n;
	for(int i =0;i<m;i++){
		an = a->n;
		n = B->length;
		b = B->next;
		for(int j =0;j<n;j++){
			bn = b->n;
			if(an.number==bn.number){
				DelteList(B,j);
				break;
			}else{
				b = b->next;
			}
		}
		a = a->next;
	}
	A->prior->next = B->next;
	a = B->prior;
	B->prior = A->prior;
	A->prior = a;
	a->next = A;
	A->length += B->length;
	return A;
}

void main(){
	NodeList *A = InitList();
	printf("--------Create the set A--------\n");
	CreateList(A);
	Node n;
	n.number = 222;
	//InsertList(A,1,n);
	PrintList(A);
	NodeList *B = InitList();
	printf("--------Create the set B--------\n");
	CreateList(B);
	PrintList(B);
	printf("----------Merge A and B----------\n");
	A = MergeList(A,B);
	PrintList(A);
	system("pause");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小黄鸭and小黑鸭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值