内部插入函数头部未更新
#include<iostream>
#include<stdlib.h>
using namespace std;
struct node {
int data;
struct node* next;
}*head = NULL;
void insert(struct node* head, int data) {
struct node * newNode ;
newNode->data = data;
newNode->next = NULL;
if (head == NULL) {
head =newNode;
}
else {
struct node* current = head;
while (current->next != NULL) {
current = current->next;
}
//newNode->next = NULL;
current->next = newNode;
}
}
void display(struct node * head) {
struct node* current = head;
while (current) {
cout << current->data<<endl;
}
}
int main()
{
insert(head, 5);
insert(head, 6);
insert(head, 56);
insert(head, 65);
insert(head, 885);
insert(head, 66);
insert(head, 00);
display(head);
}
代码的问题是您的head
在您的功能范围之外仍然是NULL
。为了更新它,你必须定义一个指向head
的指针。除此之外,还需要为newNode
动态分配内存。
void insert(struct node** head, int data) {
struct node * newNode = new node() ;
newNode->data = data;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
}
else {
struct node* current = *head;
while (current->next != NULL) {
current = current->next;
}
//newNode->next = NULL;
current->next = newNode;
}
}
Frommain()
callinsert
function as:insert(&head, 5);
.
你的代码中的另一个问题是在display
函数中,你没有将current
更新为current->next
。
while (current) {
cout << current->data << endl;
current = current->next;
}