簡體   English   中英

在C中反轉列表后,打印單鏈接列表時出現問題

[英]Problem printing the singly linked list after reversing the list in C

我已經顛倒了一個單鏈列表,也交換了頭和尾,但是在reverseList() ,輸出僅顯示列表的頭。

/* Program to create a linked list and read numbers into it until the user 
   wants and print them using functions
Author: Shekhar Hazari
Created On: 20, January 2019 */

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

struct node { int data; struct node *next; };

typedef node *list;

list head, tail;

list append(int d, list t); 
void printList(list h); 
void reverseList(list, list);

int main() {
    char more = 'Y';
    int dat;

    head = (list)malloc(sizeof(node));
    printf("Enter the first integer: ");
    scanf("%d", &dat);
    head->data = dat;
    head->next = NULL;
    tail = head;
    printf("\nWant to add more data into the list? ");
    scanf(" %c", &more);

    while (more == 'y' || more == 'y') {
        printf("Enter the integer to add to list: ");
        scanf("%d", &dat);

        tail = append(dat, tail);

        printf("\nWant to add more data into the list? ");
        scanf(" %c", &more);
    }

    printf("\nPrinting the list in the order it was entered: ");
    printList(head);

    reverseList(head, tail);
    printf("\nPrinting the list after 'reverseList': ");
    printList(head);

    return 0;
}

// function to append integer to the list 
list append(int d, list t) {
    list temp;
    temp = (list) malloc(sizeof(node));
    temp->data = d;
    t->next = temp;
    temp->next = NULL;
    t = temp;
    return t;
}

// function to print the list
void printList(list h) {
    list temp;
    temp = h;
    while (temp != NULL) {
        printf("%d\t", temp->data);
        temp = temp->next;
    }
}

// function to reverse a singly linked list 
void reverseList(list h, list t) {
    list temp1, temp2;

    temp1 = t; //temp2 = head;

    while (temp1 != h) {
        temp2 = h;

        while (temp2->next != temp1)
            temp2 = temp2->next;

        temp1->next = temp2;
        temp1 = temp2;
    }
    h = t;
    t = temp1;
    t->next = NULL;

    return;
}

例如我插入5, 10, 15, 20, 25到列表中和后reverseList()的輸出為5 我哪里做錯了?

您不能反轉列表並保持headtail指針不變。

reverseList函數應使用指向headtail指針,並將其更新以指向反向列表的第一個和最后一個節點。 此外,可以單次完成反轉單鏈列表。

這是修改后的版本:

// function to reverse a singly linked list 
void reverseList(list *headp, list *tailp) {
    list temp, last, next;

    *tailp = temp = *headp;

    if (temp) {
        while ((next = temp->next) != NULL) {
            temp->next = last;
            last = temp;
            temp = next;
        }
        *headp = last;
    }
}

來自main呼叫

reverseList(&head, &tail);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM