在上课的时候想了一下链表的双指针写法
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node* next;
}Node;
int main() {
struct node *newn = malloc(sizeof(struct node));
newn->next = NULL;
Push(&newn, 3);
Push(&newn, 4);
printQueue(newn);
return 0;
}
void Push(Node**headRef, int newData){
Node *head = *headRef;
struct node *newn = malloc(sizeof(struct node));
newn->data = newData;
newn->next = head;
head = newn;
if(head->next->data ==NULL){
return;
}
*headRef = head;
};
void printQueue(Node* l){
while(l != NULL){
printf("data is %d\n", l->data);
l = l->next;
}
printf("\n");
};
但是打印出来的是
data is 4
data is 3
data is 1530256
最后一个是内存,不知道如何去消掉这个内存
如何解决这个问题
int Pop(Node* list);
int Count(Node* head, int a);//a出现的次数
还有这两个个方法的实现
帮你调试过了,你使用的是头插法,也就是在连边的头部进行插入数据。出现你这种情况,是因为你在mian函数里创建的那个节点没有给data赋值,导致他的值是乱值。如果你在printQueue函数中不希望它输出的话,将while条件改成while (l->next != NULL);
解释:当当前节点的下一个节点等于NULL时,结束循环。也就是说,当节点在最后一个节点那里是,此时的data是乱值,判断他的下一个节点为NULL,然后结束循环。
另外,你所说的那两个节点,你自己去写吧,有问题还可以发出来提问,不能干想着别人给你答案。
问题根源:
struct node *newn = malloc(sizeof(struct node));
newn->next = NULL;
newn->data 没有初始化导致其值不可控。
修改:
struct node *newn = NULL即可。
Push函数:
功能: 添加一个节点至链表。但这功能实现也是有问题,自己可以再看看。
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,欢迎您加入CSDN!
目前问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632