【发布时间】:2018-07-29 19:03:14
【问题描述】:
我正在尝试在 C 中从头开始实现一个链表:
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node * next;
};
void insert(struct node** root, int data){
// Create a Node
struct node * temp = malloc(sizeof(struct node));
temp->data = data;
temp->next = NULL;
// Either root is NULL or not
if (*root == NULL){
*root = temp; // Directly modify the root
}
else {
struct node * t = *root;
while (t->next!=NULL){
t = t->next;
}
t->next = temp; // Append at the last
}
}
void printList(struct node * root){
while(root!=NULL){
printf("%d\t", root->data);
}
}
struct node * search(struct node* root, int key){
while (root!=NULL) {
if (root->data == key) return root;
}
return NULL;
}
int main(){
struct node * head = NULL;
insert(&head,0);
insert(&head,1);
insert(&head,2);
insert(&head,3);
insert(&head,4);
printList(head);
}
现在,当我运行程序时,我的输出是:
0 0 0 0 0 0 0 0 0 0
但是,我的列表不包含全零或 10 个元素。
我的逻辑似乎是正确的,但不知何故代码有一个错误。
顺便说一句,有没有办法避免双指针,我不能在插入链表时只使用指针吗?
【问题讨论】:
-
[c++] 语言与这个问题有什么关系?
-
@user2079303链表在c plus中实现类似
-
while(root!=NULL){root 在这个打印循环中永远不会改变。顺便说一句:这是更喜欢 for() 循环而不是 while() 循环的一个很好的理由。 -
My logic is correct but somehow code has a bug.这不是它的工作原理。乍一看,您的 printList 函数不会遍历列表,而只会打印 root->data。 -
@mourinho 在 C 中避免双指针的唯一方法是
insert返回头指针,例如:struct node *insert(struct node* root, int data) ...
标签: c algorithm data-structures linked-list