ورود

View Full Version : سوال: مشکل در تعریف لینک لیست



disiba
یک شنبه 04 آذر 1397, 20:11 عصر
سلام دوستان . من میخوام یک لینک لیست ساده درست کنم . برنامه زیر رو نوشتم ولی ارور میده . مشکل از چیه ؟ ممنون
#include "stdafx.h"
struct node
{
int data;
struct node *next;
}

int _tmain(int argc, _TCHAR* argv[])
{
node *tmp1 = new node;
node *tmp2 = new node;


tmp1->data = 5;
tmp1->next = tmp2->next;
tmp2->data = 6;
tmp2->next = NULL;

return 0;
}

farhad_shiri_ex
دوشنبه 05 آذر 1397, 10:34 صبح
باید اینطوری تعریف کنید و استفاده کنید

#include <stdio.h>
#include <stdlib.h>



typedef struct node {
int x;
struct node *next;
}lnode;

/* This won't change, or we would lose the list in memory */
lnode* root;

int pushBack(lnode* conductor , const int value){

if(root == 0){
root = malloc( sizeof(lnode) );
root->next = NULL;
root->x = 32;
}

conductor = root;
if ( conductor != 0 ) {
while ( conductor->next != 0){
conductor = conductor->next;
}
}

/* Creates a node at the end of the list */
conductor->next = malloc( sizeof(lnode) );

conductor = conductor->next;

if ( conductor == 0 ){
printf( "Out of memory" );
return 0;
}
/* initialize the new memory */
conductor->next = NULL;
conductor->x = value;
return 1;
}

void showList(){
if ( root != 0 ) { /* Makes sure there is a place to start */
while ( root->next != 0 ) {
printf( "%d\n", root->x );
root = root->next;
}
printf( "%d\n", root->x );
}
}

int main()
{

/* This will point to each node as it traverses the list */
lnode *conductor = malloc( sizeof(lnode) );
lnode *conductor2 = malloc( sizeof(lnode) );
lnode *conductor3 = malloc( sizeof(lnode) );
lnode *conductor4 = malloc( sizeof(lnode) );

pushBack(conductor , 42);
pushBack(conductor2 , 52);
pushBack(conductor3 , 62);
pushBack(conductor4 , 72);

showList();

free(root);

return 0;
}