#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
int data;
struct node *next;
struct node *prev;
};
struct node *create_node(int num)
{
struct node *p = (struct node*)malloc(sizeof(struct node));
if(p == NULL)
{
printf("error");
return NULL;
}
bzero(p,sizeof(struct node));
p->data = num;
p->prev = NULL;
p->next = NULL;
return p;
}
void insert_tail(struct node *head,struct node *new)
{
struct node *p = head;
while(p->next != NULL)
{
p = p->next;
}
p->next = new;
new->next = NULL;
new->prev = p;
}
void insert_head(struct node *head,struct node *new)
{
new->next = head->next;
if(head->next != NULL)
{
head->next->prev = new;
}
head->next = new;
new->prev = head;
// head->next->prev = new;
}
void insert_middle(struct node *head,struct node *new,int num)
{
int flag = 0;
struct node *p = head;
struct node *temp = NULL;
while(p->next != NULL)
{
p = p->next;
temp = (struct node*)malloc(sizeof(struct node));
temp->data = new->data;
if(p->data == num)
{
if(p->next == NULL)
{
p->next = new;
new->prev = p;
new->next = NULL;
flag = 1;
}
else
{
temp->next = p->next;
p->next->prev = temp;
p->next = temp;
temp->prev = p;
p = p->next;
free(temp);
temp = NULL;
flag = 1;
}
}
}
if(flag == 0)
{
printf("NO find! insert error!\n");
}
}
#if 1
int delete_node(struct node *head,int num)
{
struct node *p = head;
struct node *ptr = NULL;
while(p->next != NULL)
{
ptr = p;
p = p->next;
if(p->data == num)
{
if(p->next == NULL)
{
ptr->next = NULL;
free(p);
p = NULL;
}
else
{
ptr->next = p->next;
p->next->prev = ptr;
free(p);
p = NULL;
}
return 0;
}
}
}
#endif
struct node *display(struct node *head)
{
struct node *p = head;
while(p->next != NULL)
{
p = p->next;
printf("%d\n",p->data);
}
return p;
}
void display_tail(struct node *p)
{
while(p->prev != NULL)
{
printf("%d\n",p->data);
p = p->prev;
}
}
int main()
{
struct node *head = create_node(0);
int i = 0;
struct node *ptr = (struct node*)malloc(sizeof(struct node));
for(i = 0;i < 5;i++)
{
struct node *new = (struct node *)malloc(sizeof(struct node));
new->data = i+1;
// insert_tail(head,new);
insert_head(head,new);
}
struct node *new = (struct node*)malloc(sizeof(struct node));
new->data = 3;
insert_head(head,new);
ptr = display(head);
printf("前向遍历:\n");
display_tail(ptr);
printf("中间插入:\n");
new = (struct node *)malloc(sizeof(struct node));
new->data = 18;
insert_middle(head,new,3);
display(head);
printf("删除结点:\n");
delete_node(head,4);
display(head);
printf("再次前序遍历:\n");
display_tail(ptr);
return 0;
}
关于双链表的相关操作
最新推荐文章于 2020-12-03 14:46:36 发布