首頁  >  文章  >  後端開發  >  以C語言的迭代方法,將鍊錶的最後k個節點以相反的順序列印出來

以C語言的迭代方法,將鍊錶的最後k個節點以相反的順序列印出來

WBOY
WBOY轉載
2023-09-17 21:21:02849瀏覽

以C語言的迭代方法,將鍊錶的最後k個節點以相反的順序列印出來

我們必須以相反的順序列印鍊錶的 k 個節點。我們必須應用迭代方法來解決這個問題。

迭代方法通常使用循環執行,直到條件值為 1 或 true。

比方說, list 包含節點 29, 34, 43, 56 和 88,k 的值為 2,輸出將是直到 k 的備用節點,例如 56 和 88。

以C語言的迭代方法,將鍊錶的最後k個節點以相反的順序列印出來

範例

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("</p><p>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

以上是以C語言的迭代方法,將鍊錶的最後k個節點以相反的順序列印出來的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除