使用 C 語言迭代方法列印連結串列的後 k 個節點(逆序)


我們需要以逆序列印連結串列中的 k 個節點。我們需要使用迭代方法來解決這個問題。

迭代方法通常使用迴圈,這些迴圈在條件為 1 或 true 時執行。

假設列表包含節點 29、34、43、56 和 88,並且 k 的值為 2,則輸出將是交替的節點,直到 k,例如 56 和 88。

示例

Linked List: 29->34->43->56->88
Input: 2
Output: 56 88

由於我們需要從列表中刪除最後 k 個元素,因此最好的方法是使用棧資料結構,其中元素會被壓入棧中,從而建立列表,棧的起始元素是列表的最後一個元素,並且它們會從棧中彈出,直到第 k 次,從而給出連結串列的最後一個節點。

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

演算法

START
   Step 1 -> create node variable of type structure
      Declare int data
      Declare pointer of type node using *next
   Step 2 -> create struct node* intoList(int data)
      Create newnode using malloc
      Set newnode->data = data
      newnode->next = NULL
      return newnode
   step 3 -> Declare function void rev(struct node* head,int count, int k)
      create struct node* temp1 = head
      Loop While(temp1 != NULL)
         count++
         temp1 = temp1->next
      end
      Declare int array[count], temp2 = count,i
      Set temp1 = head
      Loop While(temp1 != NULL)
         Set array[--temp2] = temp1->data
         Set temp1 = temp1->next
      End
      Loop For i = 0 and i < k and i++
         Print array[i]
      End
   Step 4 -> In Main()
      Create list using struct node* head = intoList(9)
      Set k=3 and count=0
      Call rev(head,count,k)
STOP

示例

#include<stdio.h>
#include<stdlib.h>
// Structure of a node
struct node {
   int data;
   struct node *next;
};
//functon for inserting a new node
struct node* intoList(int data) {
   struct node* newnode = (struct node*)malloc(sizeof(struct node));
   newnode->data = data;
   newnode->next = NULL;
   return newnode;
}
// Function to reversely printing the elements of a node
void rev(struct node* head,int count, int k) {
   struct node* temp1 = head;
   while(temp1 != NULL) {
      count++;
      temp1 = temp1->next;
   }
   int array[count], temp2 = count,i;
   temp1 = head;
   while(temp1 != NULL) {
      array[--temp2] = temp1->data;
      temp1 = temp1->next;
   }
   for(i = 0; i < k; i++)
   printf("%d ",array[i]);
}
int main() {
   printf("
reverse of a list is : ");    struct node* head = intoList(9); //inserting elements into a list    head->next = intoList(76);    head->next->next = intoList(13);    head->next->next->next = intoList(24);    head->next->next->next->next = intoList(55);    head->next->next->next->next->next = intoList(109);    int k = 3, count = 0;    rev(head, count, k); //calling function to print reversely    return 0; }

輸出

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

reverse of a list is : 109 55 24

更新於: 2019年8月22日

179 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告