// 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;
}
双向链表的创建/插入/删除
最新推荐文章于 2023-10-13 20:56:33 发布