2017-06-15 13 views
0
#include <stdio.h> 

#include<stdlib.h> 

typedef struct node 
{ 
    int data; 
    int help; 
    struct node* next; 
    }Node; 

void print_list(Node* head); 
void CreateList(Node** head ,int data); 
void reverse(Node** head_ref); 



int main() 
{ 
    int i,c,a; 
    Node* list = NULL; 
    printf("How many numbers do you want? "); 
    scanf("%d",&c); 
    for(i=1;i<=c;i++) 
    { 
     printf("Enter number %d: ",i); 
     scanf("%d",&a); 
     CreateList(&list,a); 
    } 

    printf("Given linked list\n"); 
    print_list(list); 
    reverse(&list); 
    printf("\nReversed Linked list \n"); 
    print_list(list); 
    return 0; 
} 

void print_list(Node* head) 
{ 
    while(head != NULL) 
    { 
     printf("%d -> ",head->data); 
     head = head->next; 
    } 
    if(head==NULL) 
     printf("NULL"); 
    return; 
} 

void CreateList(Node** head ,int data) 
{ 
    Node *temp = (Node*) malloc(sizeof(Node));; 
    temp->data = data; 
    temp->next = *head; 
    *head = temp; 
} 

void reverse(Node** head_ref) 
{ 
    Node* prev = NULL; 
    Node* current = *head_ref; 
    Node* next; 
    while (current != NULL) 
    { 
     next = current->next; 
     current->next = prev; 
     prev = current; 
     current = next; 
    } 
    *head_ref = prev; 
} 

入力:6-> 5-> 4-> 3-> 2->:リンクされたリストが与えられる1 2 3 4 5 6C - リンクされたリスト - 逆の方法でリンク

  • 1-> NULL

  • 逆リンクリスト:1-> 2-> 3-> 4-> 5-> 6-> NULL

マイ考えた本:

  • 1-> 2-> 3-> 4-> 5-> 6-> NULL - であるに与えられるリスト

  • 6-> 5-> 4-> 3-> 2-> 1 - > NULL - 逆のリストになる

私は実際にはとても大変でしたが、普通のやり方で解決策を見つけることができませんでした。

答えて

1

create_list()関数は、チェーンの先頭に新しいノードを挿入します。は、既存の要素をにプッシュダウンします。代わりに、あなたはのように、鎖の末端にを追加することもできます


void add_at_end(Node** head ,int data) 
{ 
    Node *temp; 

     // Find the end of the chain 
    while (*head) { head = & (*head)->next ; } 

    temp = malloc(sizeof *temp); 
    temp->next = NULL; 
    temp->data = data; 
     // append 
    *head = temp; 
} 
+0

は、それが働いた、ありがとう;) – Ameer

+1

それが働いていた場合、この答えを受け入れます。感謝しないでください –

関連する問題