链接列表需要帮助无法打印我的数据.想要制作一个添加功能.在C - C++中

Vat*_*ato 1 c c++

这是我的代码.我想打印所有列表数据.但是当我写我不能引起while(llist->next != NULL) llist->nextNULL,但我不知道为什么.请帮我 :)

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;

struct rame
{
    int data;   
    struct rame *next;  
};
int main()
{ 
    struct rame *llist;
    llist = (rame*)malloc(sizeof(struct rame));
    llist->data = 10;
    llist->next = llist; 
    llist->next->data = 15;
    llist->next->next->data = 20;
    llist->next->next->next->data = 25; 
    llist->next->next->next->next = NULL;
    printf("test\n");
    if(llist->next == NULL)
    printf("%d\n",llist->data);
    else
    while(llist->next != NULL)
    {
         printf("%d\n",llist->data);          
         llist = llist->next;
    } 
 system("pause");
 return 0;   
}  
Run Code Online (Sandbox Code Playgroud)

嘿,我做了一次,但我的LOOP没有打印最后的数据.帮我 :(

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;

struct rame
{
    int data;   
    struct rame *next;  
};
int main()
{ 
    struct rame *llist;
    llist = (rame*)malloc(sizeof(struct rame));
    llist->data = 10;
    llist->next = (rame*)malloc(sizeof(struct rame));
    llist->next->data = 15;
    llist->next->next = (rame*)malloc(sizeof(struct rame));
    llist->next->next->data = 20;
    llist->next->next->next = (rame*)malloc(sizeof(struct rame));
    llist->next->next->next->data = 25; 
    llist->next->next->next->next = (rame*)malloc(sizeof(struct rame));
    llist->next->next->next->next =  NULL;
    printf("test\n");
    while(llist->next != NULL)
    {
         printf("%d\n",llist->data);          
         llist = llist->next;
    } 
 system("pause");
 return 0;   
}          
Run Code Online (Sandbox Code Playgroud)

Mat*_*Mat 6

llist->next = llist; 
Run Code Online (Sandbox Code Playgroud)

llist下一个要素就是llist它本身.您本身没有链接列表,只有一个循环回自身的元素.所以:

llist->next->data = 15;
llist->next->next->data = 20;
llist->next->next->next->data = 25; 
Run Code Online (Sandbox Code Playgroud)

所有这些修改llist->data.和:

llist->next->next->next->next = NULL;
Run Code Online (Sandbox Code Playgroud)

设置llist->nextNULL.

malloc如果要构建列表,则需要创建新的列表元素(带)并链接它们.例如:

llist = (rame*)malloc(sizeof(struct rame));
llist->data = 10;
llist->next = (rame*)malloc(sizeof(struct rame));
llist->next->data = 15;
llist->next->next = (rame*)malloc(sizeof(struct rame));
llist->next->next->data = 15;
....
Run Code Online (Sandbox Code Playgroud)

你的循环不正确:你将总是跳过最后一个条目,因为它将->next为null,因此循环体不会运行.

试试:

struct rame *cursor = llist;

while (cursor != NULL) {
  printf("%d\n", cursor->data);          
  cursor = cursor->next;
}
Run Code Online (Sandbox Code Playgroud)

您使用指向列表的第二个指针,以便llist保持不变并指向列表标题.(如果你不这样做,你将永远无法回到它,因为它是单独链接的.)