还得请吧内大佬解决一下这个问题
codeblocks吧
全部回复
仅看楼主
level 5
view◎ 楼主
C语言,链表。已经build过了,0,0,0,1,就一个函数有问题,在deletedata函数哪里出了点问题,就是删除头结点时无法删除,删除尾节点时却把最后两个节点都删了,真的很迷[狂汗],不知道该怎么改了。还请哪位大佬出手相救。
#include <stdio.h>
#include <stdlib.h>typedef struct link
{
int data;
struct link * next;
struct link * pre;
}L;
typedef struct link * P;
P construction(P head)
{
P pt = NULL,pr = NULL;
head = (P)malloc(sizeof(L));
pt = (P)malloc(sizeof(L));
head->next = pt;
pt->pre = head;
printf("input data: ");
scanf("%d",&pt->data);
while(pt->data!=0)
{
pr = (P)malloc(sizeof(L));
printf("input data: ");
scanf("%d",&pr->data);
pt->next = pr;
pr->pre = pt;
pt = pr;
}
pt->next = head;
head->pre = pt;
printf("input data of head: ");
scanf("%d",&pt->next->data);
printf("INPUT OVER.\n");
return head;
}
int length(P head)
{
int i;
P pt = head;
for (i=0;pt->next!=head;i++)
{
pt = pt->next;
}
return i+1;
}
void printdata(P head)
{
int i = 1;
P pt = head;
for (i=1;i<=length(head);i++)
{
printf("data %d:%d\n",i,pt->data);
pt = pt->next;
}
}
int insert(P head, int x)
{
P ps,pt;
int i = 0;
ps = (L*)malloc(sizeof(L));
pt = (L*)malloc(sizeof(L));
ps = head;
if (x>length(head))
{
printf("illegal input!\n");
return 0;
}
for (i=0;i<x-2;i++)
{
ps = ps->next;
}
printf("ps->data = %d\n",ps->data);
printf("input the insert data: ");
scanf("%d",&pt->data);
pt->next = ps->next;
ps->next->pre = ps;
ps->next = pt;
pt->pre = ps;
return 1;
}
P deleteData(P head, int n)
{
P pt;
int i;
if (n>length(head))
{
return NULL;
}
pt = (P)malloc(sizeof(L));
pt = head;
if (n==1)
{
head->pre = head->next;
head->next->pre = head->next;
free(head);
printf("Destruction Completed.\n");
return head->next;
}
else
{
for (i=0;i<n-1;i++)
{
pt = pt->next;
}
pt->pre->next = pt->next;
pt->next->pre = pt->pre;
free(pt);
printf("Destruction Completed.\n");
return head;
}
}
int main()
{
P head = NULL;
int a,b,c,d,f;
head = construction(head);
printdata(head);
printf("Do you want to insert data in the line?\n");
scanf("%d",&a);
while(a!=0)
{
printf("input location: ");
scanf("%d",&b);
c = insert(head,b);
if (c==0)
{
printf("fail to insert!\n");
exit(0);
}
printdata(head);
printf("Do you want to insert data in the line?\n");
scanf("%d",&a);
}
printf("Do you want to delete any data?\n");
scanf("%d",&d);
while(d!=0)
{
printf("input location: ");
scanf("%d",&f);
head = deleteData(head,f);
if (head!=NULL)
{
printdata(head);
}
else
{
printf("Fail to operate!\n");
}
printf("Do you want to delete any data?\n");
scanf("%d",&d);
}
printf("Hello world!\n");
return 0;
}
2019年03月20日 14点03分 1
1