鏈表的創建和輸出函式都沒問題,就是執行完洗掉函式后不能正常輸出了,我debug了一下,發現是如果洗掉第二個數,那第三個數的data就會變成0x...之類的,我覺得是洗掉時第一個數和第二個數沒連接好,但又看不出問題
void Creat(Node *h)
{
int i,n;
Node *p , *node;
h->next = NULL;
p = h;
srand(time(0));
printf("請輸入結點數量:");
scanf("%d",&n);
for (i = 0; i < n; i++)
{
node = (Node*)malloc(sizeof(Node));
node->data = rand() % n;
p->next = node;
p = node;
}
p->next = NULL;
}
void Delete(Node *h) //n為被洗掉資料所在的位置
{
int i,n;
Node *p=h;
Node *q;
printf("請輸入要洗掉第幾個資料:");
scanf("%d",&n);
for (i = 1; i < n; i++)
{
p = p->next;
}
q = p;
p->next = (q->next)->next;
free(q->next);
}
void Print(Node *h)
{
Node *p;
p = h;
printf("資料如下:");
while (p->next != NULL)
{
p = p->next;
printf("%d ",p->data);
}
printf("\n");
}
uj5u.com熱心網友回復:
最好畫個圖這樣更清晰一些修改如下
for (i = 1; i < n; i++)
{
p = p->next;
}
q = p->next;
p->next = q->next;
free(q)
uj5u.com熱心網友回復:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct node {
int data;
struct node *next;
}Node;
//void Creat(Node *h)
void Creat(Node **h)
{
int i,n;
Node *p , *node;
//h->next = NULL;
//p = h;
srand(time(0));
printf("請輸入結點數量:");
scanf("%d",&n);
for (i = 0; i < n; i++)
{
node = (Node*)malloc(sizeof(Node));
node->data = rand() % n;
if (*h == NULL) {
(*h) = node;
p = (*h);
} else {
p->next = node;
p = node;
}
}
p->next = NULL;
}
//void Delete(Node *h) //n為被洗掉資料所在的位置
void Delete(Node **h) //n為被洗掉資料所在的位置
{
int i,n;
Node *p=*h;
Node *q;
printf("請輸入要洗掉第幾個資料:");
scanf("%d",&n);
if (n == 1) {
*h = (*h)->next;
free(p);
return;
}
for (i = 1; i < n-1; i++)
{
if (!p)
break;
p = p->next;
}
if (!p) {
printf("Can't find it!\n");
return;
}
//q = p;
q = p->next;
if (!q) {
printf("Can't find it!\n");
return;
}
//p->next = (q->next)->next;
p->next = q->next;
//free(q->next);
free(q);
}
void Print(Node *h)
{
Node *p;
p = h;
printf("資料如下:");
//while (p->next != NULL)
while (p != NULL)
{
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
int main(void)
{
Node *head = NULL;
Creat(&head);
Print(head);
Delete(&head);
Print(head);
return 0;
}
供參考~
樓主的創建鏈表,洗掉鏈表以及輸出都有問題~
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/19202.html
標籤:C語言
上一篇:資料結構順序表C++類實作
