双向链表的创建/插入/删除

// DataStructure.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

typedef struct Teacher
{
	int data;
	Teacher * left;
	Teacher * right;
}Node;

Node * create(int* data,int length){
	if (data==NULL||length<=0)
	{
		return NULL;
	}

	Node *head=NULL;
	Node *p=NULL;
	for (int i = 0; i < length; i++)
	{
		Node * node = new Node();
		node->data=data[i];
		node->right=NULL;
		
		if (head==NULL)
		{
			head=node;
		}
		else
		{
			p->right=node;
		}
		node->left=p;
		p=node;
	}

	return head;
}

void print(Node *head){
	Node*p=head;
	while (p!=NULL&&p->right!=NULL)
	{
		printf("%d\t",p->data);
		p=p->right;
	}
	
	if (p!=NULL)
	{
		printf("%d\n",p->data);
	}
	while (p!=NULL)
	{
		printf("%d\t",p->data);
		p=p->left;
	}
	printf("\n");
}

void printBackForward(Node *head){
	Node*p=head;
	if (p!=NULL&&p->right!=NULL)
	{
		printBackForward(p->right);
	}
	
	if(p!=NULL)
	{
		printf("%d\t",p->data);
	}
}

Node *insert(Node **head,int index,int value){
	if (head==NULL)
	{
		return NULL;
	}
	if (index<=0)
	{
		Node *node =new Node();
		node->data=value;
		node->left=NULL;
		node->right=*head;
		(*head)->left=node;
		*head=node;
	}
	else
	{
		Node *p=*head;
		Node *q=p;
		int i=0;
		while (p!=NULL&&i<index)
		{
			++i;
			q=p;
			p=p->right;
		}

		if(q!=NULL){
			Node *node =new Node();
			node->data=value;
			node->left=q;
			node->right=p;
			q->right=node;
			if (p!=NULL)
			{
				p->left=node;
			}
		}
	}
	
	return *head;
}

void deleteNode(Node **head,int value){
	if (head==NULL)
	{
		return ;
	}

	Node *p=*head;
	Node *q=p;
	while (p!=NULL)
	{
		if (p->data==value)
		{
			if (p==*head)//头
			{
				*head=p->right;
				if (*head!=NULL)//有不止一个元素
				{
					(*head)->left=NULL;
				}
			}
			else if (p->right==NULL)//尾
			{
				q->right=NULL;
			}
			else //中间
			{
				q->right=p->right;
				p->right->left=q;
			}

			delete p;
			break;
		}

		q=p;
		p=p->right;
	}
}

Node *tail(Node *head){
	Node *p=head;
	while (p!=NULL&&p->right!=NULL)
	{
		p=p->right;
	}

	return p;
}

int _tmain(int argc, _TCHAR* argv[])
{
	int data[]={1,4,2,5,3};
	Node *head=create(data,5);
	print(head);
	deleteNode(&head,1);
	print(head);
	deleteNode(&head,3);
	print(head);
	deleteNode(&head,2);
	print(head);
	return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值