在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.