2017-12-14 9 views
-3

처음부터 끝까지 하나씩 링크 된 목록을 인쇄하십시오.처음부터 끝까지 하나씩 링크 된 목록 인쇄

예 :

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

예상 출력 :

1,6,2,5,3,4

+1

코드를 묻지 마십시오. 먼저 시도한 코드를 보여주고 문제를 묻습니다. 우리는 당신의 가내 노동을 완성하기 위해 여기에 있지 않습니다. –

답변

-1

Checked!

#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); 
    printlist(head);  
    arrange(&head); 
    printlist(head);  
    return 0; 
}