在C語言中列印連結串列的反轉而不實際反轉


本任務是使用遞迴函式列印給定連結串列的反轉。程式必須列印反轉,但不反轉列表,這意味著節點的順序保持不變。

在這裡,程式將移動包含第一個節點地址的頭指標到下一個節點,直到檢查到儲存在列表最後一個節點中的NULL,並列印頭節點的資料。

示例

Input: 29 34 43 56
Output: 56 43 34 29

首先,節點被插入到列表中,一個指標將開始指向被插入的節點。建立最終列表後,假設temp指標將用第一個節點指標初始化,它會一直遞增,直到節點的下一個地址為NULL(因為最後一個節點不指向任何內容),然後從最後一個節點遍歷到頭指標。它將顯示列表的反轉,而實際上並沒有反轉列表。

以下程式碼顯示了給定演算法的C語言實現。

演算法

START
   Step 1 -> create node variable of type structure
      Declare int data
      Declare pointer of type node using *next
   Step 2 ->Declare function void reverse(node* head)
      IF head == NULL
         return
      Call reverse(head->next)
      Print head->data
   Step 3 -> Declare Function void push(node** header, char newdata)
      Allocate memory using malloc
      Set newnode->data = newdata
      Set newnode->next = (*header)
      Set (*header) = newnode
   Step 4 ->In Main()
      Create list using node* head = NULL
      Insert elements through push(&head, 56)
      Call reverse(head)
STOP

示例

#include<stdio.h>
#include<stdlib.h>
//creating structure for a node
struct node {
   int data;
   node* next;
};
//function to print reverse of the data in the list
void reverse(node* head) {
   if (head == NULL)
      return;
   reverse(head->next);
   printf("%d ", head->data);
}
//function to puch the node in the list
void push(node** header, char newdata) {
   struct node* newnode = (struct node*)malloc(sizeof(struct node));
   newnode->data = newdata;
   newnode->next = (*header);
   (*header) = newnode;
}
int main() {
   node* head = NULL;
   push(&head, 56); //calling function to push 56 in the list
   push(&head, 43);
   push(&head, 34);
   push(&head, 29);
   reverse(head);
   return 0;
}

輸出

如果我們執行上面的程式,它將生成以下輸出。

reverse of a linked list 56 43 34 29

更新於:2019年8月22日

269 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.