双向链表的结构:数据域,以及两个指针域,其中一个指针指向前驱节点,一个指针指向后继节点。
//twowaylist.cpp
#include"twowaylist.h"
//思路:分插入的位置情况分别实现,插入的位置为1和其它。
void insert_twowaynode(twowaylist* clist, int pos, int value)
{
int i = 0;
twowaynode* node = (twowaynode*)malloc(sizeof(twowaynode));//创建空节点(待插入的节点)
node->data=value;
node->next = NULL;
node->prior = NULL;
if (pos == 1)//插入的位置为1
{
if (clist->length==0)//当前链表为空
{
clist->next = node;//头节点的指针域直接指向前面创建的新节点,新节点的next指针和prior指针前面已经赋初值NULL,这里不需在赋值
clist->length++;
return;
}
//若插入的位置为1,且当前链表不为空
node->next = clist->next;
clist->next = node;
node->next->prior = node;
}
twowaynode* currnode = clist->next;//若插入的位置不是1,则从第一个节点遍历,找到待插入节点的前一个节点
for (i = 1; currnode&&i < pos - 1; i++)
{
currnode = currnode->next;//currnode为待插入节点的前一个节点
}
if (currnode)
{
node->prior = currnode;
if (currnode->next)
{
currnode->next->prior = node;
}
node->next = currnode->next;
currnode->next = node;
clist->length++;
}
}
void show_node(twowaylist* clist)
{
int i = 0;
twowaynode* node = clist->next;
if (!node || clist->length == 0)
{
printf("链表为空:!");
return;
}
for (i = 1; i <=clist->length; i++)
{
printf("%d\t", node->data);
node = node->next;
}
}
void del_twowaynode(twowaylist* clist, int pos)
{
int i = 0;
if (pos == 1)
{
twowaynode* node = clist->next;
if (node)
{
clist->next = node->next;
if (node->next)
{
node->next->prior = NULL;
}
free(node);
clist->length--;
}
return;
}
twowaynode* currnode = clist->next;
for (i = 1; currnode&&i<pos ; i++)
{
currnode = currnode->next;//currnod为删除节点
}
if (currnode)
{
if (currnode->next)
{
currnode->next->prior = currnode->prior;
}
currnode->prior->next = currnode->next;
free(currnode);
clist->length--;
}
return;
}
//twowaylist.h
#ifndef _twowaylist_h
#define _twowaylist_h
#include<stdio.h>
#include<iostream>
#include<stdlib.h>
//删除和插入节点需要修改4个指针
typedef int datatype;
typedef struct twowaynode
{
struct twowaynode * prior; //指向直接前趋
datatype data;//节点数据
struct twowaynode * next; //指向直接后继
}twowaynode;
typedef struct twowaylist
{
datatype length;//用于记录节点个数
twowaynode* next;//用于指向节点
}twowaylist;
extern void insert_twowaynode(twowaylist* clist, int pos, int value);
extern void show_node(twowaylist* clist);
extern void del_twowaynode(twowaylist* clist, int pos);
#endif
//main.cpp
#include"twowaylist.h"
int main(void)
{
int i = 0;
twowaylist* clist = (twowaylist*)malloc(sizeof(twowaylist));//头节点指向头指针
clist->length = 0;
clist->next = NULL;
for (i = 1; i < 10; i++)
{
insert_twowaynode(clist, i, i * 2);//插入元素
}
show_node(clist);//打印
del_twowaynode(clist,4);//删除第四个元素
printf("\n");
show_node(clist);//打印
system("pause");
return 0;
}
插入的节点位置为1的情况