在C中反转列表后,打印单链接列表时出现问题

时间:2019-01-20 20:59:34

标签: c linked-list singly-linked-list

我已经颠倒了一个单链列表,并且交换了头和尾,但是在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。我哪里出错了?

1 个答案:

答案 0 :(得分:0)

您不能反转列表,并保持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;
    }
}

以{p>

main