单链表的几种基本操作程序段,已经编译通过,但无法正常显示。 求高手在此基础上修正。

2025-06-28 17:42:39
推荐回答(1个)
回答1:

第一个内部保护错出在了下面这个函数:
void insert_after(linklist *p,datatype x)
{
linklist *s;
s->data=x; //s指针没有初始化,也即是s的值是个随机值。
s->next=p->next;
p->next=s;
s=(linklist*)malloc(sizeof(linklist));
}

注意:s指针在没有初始化的时候就给他的成员赋值,这是绝对不可以的。

enjoy!

============================================
给你一个单链表删除的例子程序,包括了创建和节点个数的统计操作,可以参考一下。这个程序在VC6下编译通过,并且运行正确

#include
#include

#define FALSE 0
#define TRUE 1

typedef struct NODE
{
struct NODE *link;
int value;
} Node;

Node *create()
{
Node *head, *tail, *p;
int x;
char str;

head = tail = NULL;
printf("Input data.\n");
while(1 == scanf("%d", &x))
{
p = (Node*)malloc(sizeof(Node));

p->value = x;
p->link = NULL;
if(head == NULL)
head = tail = p;
else
{
tail->link = p;
tail = p;
}
}

scanf("%c", &str);

return head;
}

int sll_remove(Node **linkp, Node *deleted)
{
Node *current;

while((current = *linkp)!= NULL && current != deleted)
linkp = ¤t->link;

if(current == deleted)
{
*linkp = current->link;
free(current);
return TRUE;
}
else
return FALSE;
}

int sll_count_nodes(Node *root)
{
int count;

for(count = 0; root != NULL; root = root->link)
++count;

return count;
}
void sll_free(Node *head)
{
Node *p;

while(head)
{
p = head;
head = head->link;

free(p) ;
}
head = NULL;
}

void sll_print(Node *p)
{
while(p)
{
printf("%d\n", p->value);
p = p->link;
}
}

void main()
{
Node *head, *p, *del;
int number, m;

p = head = create(); /* 创建单链表 */

sll_print(p); /* 打印单链表 */

/* 统计单链表节点个数 */
printf("the count of node is %d\n",
number = sll_count_nodes(head));

/* 按照节点位置删除节点,序号从开始 */
printf("please input the order number: ");
scanf("%d", &m);

if(m < number)
{
p = del = head;
while(m > 0) /* 找到要删除的节点 */
{
--m;
del = del->link;
}
if(sll_remove(&p, del)) /* 删除节点 */
{
head = p;
printf("the node is deleted!\n");
printf("new list after deleting: \n");
sll_print(p); /* 打印单链表 */
}
}
else
printf("not found the node!\n");

sll_free(head);
printf("nodes in sll have been released!\n");
}