使用代码块在链表的开头插入节点

inserting node in the beginning of linked list using codeblocks

本文关键字:开头 插入 节点 链表 代码      更新时间:2023-10-16

当我在链表的开头插入节点时,节点入到开头并显示。 如果我单独调用 display,那么它不起作用,并且对于在特定 LOC 和末尾插入节点,调用显示函数效果很好。

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
typedef struct node {
int data;
struct node* next;
} node;
node* create(int n)
{
node* temp = NULL;
node* head = NULL;
node* p;
int i;
for (i = 0; i < n; i++) {
temp = (node*)malloc(sizeof(node));
cout << "enter the data for node number " << i << endl;
cin >> temp->data;
temp->next = NULL;
if (head == NULL) {
head = temp;
}
else {
p = head;
while (p->next != NULL) {
p = p->next;
}
p->next = temp;
}
}
return head;
}
node* insertatbeg(node* head)
{
node* temp = NULL;
temp = (node*)malloc(sizeof(node));
cout << "nenter the data for first node" << endl;
cin >> temp->data;
temp->next = head;
head = temp;
return head;
}
void display(node* head)
{
node* t = NULL;
t = head;
while (t != NULL) {
cout << t->data << "->";
t = t->next;
}
}
node* insertatspecloc(node* head)
{
int n;
node* temp = NULL;
node* t = head;
temp = (node*)malloc(sizeof(node));
cout << "enter the data of node after which you want to insert the 
node "<<endl;
cin
>> n;
cout << "nenter the data for last node" << endl;
cin >> temp->data;
while (t->data != n) {
t = t->next;
}
temp->next = t->next;
t->next = temp;
return head;
}
node* insertatend(node* head)
{
node* temp = NULL;
temp = (node*)malloc(sizeof(node));
cout << "nenter the data for last node" << endl;
cin >> temp->data;
temp->next = NULL;
node* q;
q = head;
while (q->next != NULL) {
q = q->next;
}
q->next = temp;
return head;
}
int main()
{
int n, a;
struct node* head = NULL;
cout << "enter the number of nodes u want to add";
cin >> n;
head = create(n);
display(head);
cout << "npress 1 to add node at the beginning";
cout << "npress 2 to add node at the specific location";
cout << "npress 3 to add node at the endn";
cin >> a;
if (a == 1) {
insertatbeg(head);
cout << "nlinked list after insertion:n";
display(head);
}
if (a == 2) {
insertatspecloc(head);
cout << "nlinked list after insertion:n";
display(head);
}
if (a == 3) {
insertatend(head);
cout << "nLinked list after insertion:n";
display(head);
}
}

当你调用insertatbeg(head);时,head指针的副本作为函数的参数传递,然后在函数中修改局部变量(head的副本(

node *insertatbeg(node *head)
{
node *temp=NULL;
temp=(node*)malloc(sizeof(node));
cout<<"nenter the data for first node"<<endl;
cin>>temp->data;
temp->next=head;
head=temp; // assign to local variable <---
return head;
}

并且由于这个原因,在执行插入head不会更新。insertatbeg返回指针,以便您可以通过调用来解决问题

head = insertatbeg(head);

或者你可以在上面行中调用函数而不分配,但你应该通过引用传递head以便能够修改函数中的原始传递对象:

node *insertatbeg(node *& head) // pass pointer by reference
{
node *temp=NULL;
//...
head = temp; // now it works