问题描述
- 链表相关问题。。1是删除,当删除头节点的时候,会出现死循环 2插入代码写好,但是没有实现插入的功能
- int main()
{
int i = 0;
int place = 0;
int nodeData;
char c;
struct Link *head = NULL;//指向链表头
printf(""Do you want to append a new node(Y/N)"");
scanf("" %c""&c);
while(c=='Y' || c=='y')
{
head = AppendNode(head);
DispLink(head);//显示当前各节点信息
printf(""Do you want to append a new node(Y/N)"");
scanf("" %c""&c);
i++;
}
printf(""%d new nodes have been appended!n""i);
printf(""please input the nodeData you want to delete:"");
scanf(""%d""&nodeData);
DeleteNode(headnodeData);
DispLink(head);
printf(""please input the nodeData you want to insert:"");
scanf(""%d""&nodeData);
printf(""输入插入的位置"");
scanf(""%d""&place);
InsertNode01(headnodeDataplace);
DispLink(head);
//InsertNode(headnodeData);//DeleteMemory(head);//释放分配内存return 0;
}
struct Link *DeleteNode(struct Link *headint nodeData)//链表的删除
{
struct Link *p = head*pr = head;
if (head == NULL)//首先需要判断链表是否为空!若空!无需执行删除操作!
{
printf(""No Linked Table!n"");
return(head);
}
while(nodeData != p->data && p->next != NULL)//若没找到nodeData且未到表尾,则继续找!
{
pr = p;
p = p->next;
}
if (nodeData == p->data)
{
if(p == head)//判断是否删除首节点
{
head = p->next;//
}
else
{
pr->next = p->next;
}
free(p);
}
else
{
printf(""this Node has not been found!"");
}
return head;struct Link *InsertNode01(struct Link *headint nodeDataint i)
{ int j=1;struct Link *pr = head *p *temp = NULL;
p = (struct Link *)malloc(sizeof(struct Link));
if(p == NULL)
{
printf(""NO enough memory"");
exit(0);
}
p->next = NULL;//置新节点的指针域为空
p->data = nodeData;//为新节点赋数据域的值
if(head == NULL)//插入新节点前,对原链表的一个判断,不同情况插入的方法不同
{
head = p;
}
else
{ if(i = 1)
{
p->next = head;
head = p;} else { while(j < i && pr->next != NULL) { temp = pr; pr = pr->next; j++; } if(j = i) { pr = temp; p->next = pr->next; pr->next = p; } else { pr -> next = p; } }}
return(head);
};
解决方案
DeleteNode(headnodeData);
DispLink(head);
删除头后,头指针没有移动,在disp还是删除的头的信息。
InsertNode01(headnodeDataplace);
DispLink(head);
中间位置应该可以插入成功,但是头还是有没有指向新的头。