数据结构-双向列表

本文展示了如何在C语言中创建和操作双向列表。通过`GetNewNode`函数创建新节点,然后使用头插法`InsertAtHead`和尾插法`InsertAtTail`进行节点插入。同时提供了正向和反向遍历打印列表的方法`Print`和`ReversePrint`。在主函数中,对这些操作进行了实例演示。
摘要由CSDN通过智能技术生成

数据结构-双向列表

#include<stdio.h>
#include<stdlib.h>
struct Node
{
	int data;
	struct Node* prev;
	struct Node* Next;
}

struct Node* head;

struct Node* GetNewNode(int x)
{
	struct Node* newNode  = (struct Node*)malloc(sizeof(struct Node));
	newNode->data = x;
	newNode->prev = NULL;
	newNode->next = NULL;
	return newNode;
}
//头插法
void InsertAtHead(int x)
{
	struct Node* newNode = GetNewNode(int x);
	if(head == NULL) 
	{
		head = newNode;
		return;
	}
	head->prev = newNode;
	newNode->next = head;
	head = newNode;
}
//尾插法
void InsertAtTail(int x)
{
	struct Node* newNode = GetNewNode(x);
	struct Node* temp = head;
	if(head == NULL)
	{
		head = newNode;
		return;
	}	
	while(temp->next != NULL) temp = temp->next;
	temp->next = newNode;
	newNode->prev = temp;
}
//正向输出
void Print()
{
	struct Node* temp = head;
	printf("Forward: ");
	while(temp != NULL)
	{
		printf("%d",temp->data);
		temp = temp->next;
	}
	printf("\n");
}
//反向输出
void ReversePrint()
{
	struct Node* temp = head;
	if(temp == NULL) return;
	while(temp->next != NULL)
	{
	 	temp = temp ->next;
	 }
	printf("Reverse: ");
	while(temp != NULL)
	{
		printf("%d ",temp->data);
		temp = temp->prev;
	}
	printf("\n");
}

int main()
{
	head = NULL;
	InsertAtTail(2);Print();ReversePrint();
	InsertAtTail(4);Print();ReversePrint();
	InsertAtHead(6);Print();ReversePrint();
	InsertAtTail(8);Print();ReversePrint();
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值