只做了一些編輯,我試着你說的但它沒有工作,所以我嘗試了一些我更熟悉一些,但它似乎沒有正常工作。它打印信息奇怪然後崩潰..例如: 當我輸入9-8-7-6-5-4-3-2-1然後0打印,它打印回給我0-0-0-9 -1-2-3-4-5-6-7-8然後崩潰? 當我輸入1-2-3-4-5-6-7-8-9然後0打印,它打印回給我0-0-0-1-2-3-4-5-6-7 -8-9然後崩潰。打印一個有序的鏈接列表
#include <stdio.h>
#include <stdlib.h>
struct listNode{
int data; //ordered field
struct listNode *next;
};
//prototypes
void insertNode(struct listNode *Head, int x);
int printList(struct listNode *Head);
int freeList(struct listNode *Head, int x);
//main
int main(){
struct listNode Head = {0, NULL};
int x = 1;
int ret = 0;
printf("This program will create an odered linked list of numbers greater"
" than 0 until the user inputs 0 or a negative number.\n");
while (x > 0){
printf("Please input a value to store into the list.\n");
scanf("%d", &x);
insertNode(&Head, x);
}
ret = printList(&Head);
}
void insertNode(struct listNode * Head, int x){
struct listNode *newNode, *current;
newNode = malloc(sizeof(struct listNode));
newNode->data = x;
newNode->next = NULL;
current = Head;
while (current->next != NULL && current->data < x)
{
current = current->next;
}
if(current->next == NULL){
current->next = newNode;
}
else{
newNode->next = current->next;
current->next = newNode;
}
}
int printList(struct listNode * Head){
struct listNode *current = Head;
while (Head != NULL){
printf("%d \n", *current);
current = current->next;
}
}
你能給我一個例子,說明我是如何從第一個節點開始的,打印出來並轉到下一個節點?我知道如何通過數組來做這種事情,但不通過結構體/鏈接列表 – user1801067
您只需保存對當前節點的引用,然後移動到下一個項目就是使currentNode = currentNode-> next。還提供一個檢查,看下一個!= null(下一個) –
是否不會將當前節點放在列表中最近放置的位置?我將如何通過列表進入後退字詞。 – user1801067