-4

美好的一天......我想制作一个链接列表以在 C++ 中从最后一个到第一个显示列表,因为 ii 添加 29->36->15->1 我想成为 1->15->36->29 喜欢这是我通常做的

void DisplayNormal()
    {
        linkedlist *temp;
        temp = head;

        while (temp->next != NULL)
        {

            cout << "list Number : " << temp->ListNum << endl;
            cout << "Student Ceel Phone  : " << temp->number << endl;
            cout << "-------------------------------" << endl;
            temp = temp->next;
        }
        if (temp->next == NULL)
        {
            cout << "list Number : " << temp->ListNum << endl;
            cout << "Student Ceel Phone  : " << temp->number << endl;
            cout << "-------------------------------" << endl;
        }

    }
4

2 回答 2

3

有点难以理解你的问题。你的意思是如果数据是 29->36->15->1 在链表中然后显示它 1->15->36->29 或者如果数据按规则顺序给出 29、36、15、1,你想要制作链表 1->15->36->29?

我猜你想要第一个。所以我推荐使用递归函数。

typedef struct linkedlist linkedlist;
struct linkedlist{
    int data;
    struct linkedlist* next;
};
void displayReversed(linkedlist* current ) {

  if( current == NULL ) return;
  displayReversed(current->next);
  cout << current->data << endl;
}
于 2016-01-05T00:42:19.797 回答
0

我认为,最好的方法是在显示之前之后反转链表,因为我们改变了原始链表的方向,而不是它的副本。您可以在 O(n) 中反转链表,在 O(n) 中显示所有元素,这就是算法最终时间复杂度为 O(n) 的原因。

class Node
{
    Node *next;
    int val;
};

使用我的这种链表表示,您可以这样做:

Node* reverseLinkedList(Node *head)
{
    Node *prev = NULL;
    Node *current = head;
    Node *next;
    while (current) {
        next = current->next;
        current->next = prev;
        prev = current;
        current = next; 
    }
    head = prev;
}

你的完整功能是:

void DisplayReversed(Node *head)
{
    reverseLinkedList(head);

    displayNormal(*head);

    reverseLinkedList(head);
}
于 2016-01-05T00:54:46.833 回答