在C程式中,無需額外空間且不修改連結串列結構地列印連結串列的反轉。


任務是從連結串列的末尾開始列印節點,不使用額外的空間,這意味著不應該有任何額外的變數,而指向第一個節點的頭指標將被移動。

示例

Input: 10 21 33 42 89
Output: 89 42 33 21 10

有很多方法可以反向列印連結串列,例如遞迴方法(使用額外空間)、反轉連結串列(需要修改給定的連結串列)、將元素壓入堆疊然後彈出並逐個顯示元素(需要O(n)的空間),但這些方法似乎比O(1)使用了更多空間。

為了在不使用超過O(1)空間的情況下實現結果,我們可以:

  • 計算連結串列中節點的數量
  • 從i = n迴圈到1,並列印第i個位置的節點。

演算法

START
Step 1 -> create node variable of type structure
   Declare int data
   Declare pointer of type node using *next
Step 2 ->Declare function int get(struct node* head)
   Declare variable as int count=0
   Declare struct node *newme=head
   Loop While newme!=NULL
      Increment count by 1
      Set newme = newme->next
   End
   Return count
Step 3 -> Declare Function void push(node** headref, char newdata)
   Allocate memory using malloc
   Set newnode->data = newdata
   Set newnode->next = (*headref)
   Set (*headref) = newnode
Step 4 -> Declare function int getN(struct node* head, int n)
   Declare struct node* cur = head
   Loop for int i=0 and i<n-1 && cur != NULL and i++
   Set cur=cur->next
   End
Return cur->dataStep 5 -> Declare function void reverse(node *head)
   Declare int n = get(head)
   Loop For int i=n and i>=1 and i—
      Print getN(head,i)
   End
Step 6 ->In Main()
   Create list using node* head = NULL
   Insert elements through push(&head, 89)
   Call reverse(head)
STOP

示例

#include<stdio.h>
#include<stdlib.h>
//node structure
struct node {
   int data;
   struct node* next;
};
void push(struct node** headref, int newdata) {
   struct node* newnode = (struct node*) malloc(sizeof(struct node));
   newnode->data = newdata;
   newnode->next = (*headref);
   (*headref) = newnode;
}
int get(struct node* head) {
   int count = 0;
   struct node* newme = head;
   while (newme != NULL){
      count++;
      newme = newme->next;
   }
   return count;
}
int getN(struct node* head, int n) {
   struct node* cur = head;
   for (int i=0; i<n-1 && cur != NULL; i++)
      cur = cur->next;
   return cur->data;
}
void reverse(node *head) {
   int n = get(head);
   for (int i=n; i>=1; i--)
      printf("%d ", getN(head, i));
}
int main() {
   struct node* head = NULL; //create a first node
   push(&head, 89); //pushing element in the list
   push(&head, 42);
   push(&head, 33);
   push(&head, 21);
   push(&head, 10);
   reverse(head); //calling reverse function
   return 0;
}

輸出

如果執行上述程式,它將生成以下輸出

89 42 33 21 10

更新於:2019年8月22日

357 次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

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