创建一个长度为6的双链表,要求在第三个结点之前任意插入一个新结点,并输出结果
代码如下,如有帮助,请帮忙采纳一下,谢谢。
代码:
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *pre,*next;
};
int main()
{
struct Node* head = 0,*p,*t;
int i,data;
int pos;
printf("请输入6个数字:");
for (i=0;i<6;i++)
{
p = (struct Node*)malloc(sizeof(Node));
scanf("%d",&data);
p->data = data;
p->next = NULL;
if (head == 0)
{
head = p;
head->pre = NULL;
t = head;
}else
{
t->next = p;
p->pre = t;
t = p;
}
}
printf("请输入插入位置(1-3)和数据,以空格分隔:");
scanf("%d %d",&pos,&data);
p = (struct Node*)malloc(sizeof(Node));
p->data = data;
p->pre = NULL;
p->next = NULL;
if(pos == 1)
{
p->next = head;
head->pre = p;
head = p;
}else
{
t = head;
i = 1;
while(i<pos-1)
{
t = t->next;
i++;
}
p->next = t->next;
p->pre = t;
t->next = p;
}
//显示:
t = head;
while(t)
{
printf("%d ",t->data);
t = t->next;
}
//释放空间
while(head)
{
t = head->next;
free(head);
head = t;
}
head =0;
return 0;
}
假设第三个节点为q,第二个节点为p,新节点为r
r->next = q;
r->prev = p;
q->prev = r;
p->next = r;