//creaing a linked list
#include <stdio.h>
#include <iostream>
using namespace std;
struct node {
int data;
node *next;
};
node *head = NULL;
node *tail = NULL;
这是添加到链表的前面
void addToFront(int insert){
node *temp = new node();
temp->data = insert;
temp->next = head;
head = temp;
}
这将横向链表
void Transverse(){
node *temp1 = new node();
temp1 = head;
while(temp1!=NULL){
cout << temp1->data << endl;
temp1 = temp1 ->next;
tail = temp1;
}
}
通过添加到后退函数
,这是我遇到问题的代码的一部分void addToBack(int insert){
node * temp = new node();
temp -> data = insert;
temp -> next = NULL;
if(head==NULL){
head=temp;
}
else{
node * temp2= new node();
while(temp2!=NULL){
temp2 = temp2 -> next;
}
temp2->next= temp;
}
}
int main(){
addToBack(4);
addToFront(1);
addToFront(2);
addToFront(3);
addToBack(4);
Transverse();
return 0;
}
答案 0 :(得分:0)
在else分支中你可能想要这个:
node * temp2 = head;
while(temp2->next != NULL){
temp2 = temp2 -> next;
}
temp2->next= temp;