【问题标题】:Print a singly linked list from start and end one by one从开始到结束一个接一个地打印一个单链表
【发布时间】:2017-12-14 06:02:13
【问题描述】:

从头到尾一一打印单链表。

示例:

1->2->3->4->5->6

预期输出:

1,6,2,5,3,4

【问题讨论】:

  • 不要茫然地索要代码。首先显示您尝试的代码,然后询问其中的问题。我们不是来完成你的家庭作业的。

标签: c++11 data-structures linked-list


【解决方案1】:

检查!

#include<bits/stdc++.h>
using namespace std;

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

Node* newNode(int key)
{
    Node *temp = new Node;
    temp->data = key;
    temp->next = NULL;
    return temp;
}

void reverselist(Node **head)
{
    Node *prev = NULL, *curr = *head, *next;

    while (curr)
    {
        next = curr->next;
        curr->next = prev;
        prev = curr;
        curr = next;
    }

    *head = prev;
}

void printlist(Node *head)
{
    while (head != NULL)
    {
        cout << head->data << " ";
        if(head->next) cout << "-> ";
        head = head->next;
    }
    cout << endl;
}

void arrange(Node **head)
{
    Node *slow = *head, *fast = slow->next;
    while (fast && fast->next)
    {
       slow = slow->next;
       fast = fast->next->next;
    }

    Node *head1 = *head;
    Node *head2 = slow->next;
    slow->next = NULL;
    reverselist(&head2);
    *head = newNode(0); 
    Node *curr = *head;
    while (head1 || head2)
    {
        if (head1)
        {
            curr->next = head1;
            curr = curr->next;
            head1 = head1->next;
        }

        if (head2)
        {
            curr->next = head2;
            curr = curr->next;
            head2 = head2->next;
        }
    }
    *head = (*head)->next;
}

int main()
{
    Node *head = newNode(1);
    head->next = newNode(2);
    head->next->next = newNode(3);
    head->next->next->next = newNode(4);
    head->next->next->next->next = newNode(5);
    head->next->next->next->next->next = newNode(6);
    printlist(head);    
    arrange(&head);   
    printlist(head);    
    return 0;
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-13
    • 1970-01-01
    • 1970-01-01
    • 2020-08-04
    • 2015-06-30
    • 2020-07-27
    • 1970-01-01
    相关资源
    最近更新 更多