C語言連結串列交替節點列印(迭代法)


在這個問題中,程式必須使用迭代方法列印給定連結串列中的交替節點,即跳過一個列印另一個。

迭代方法通常使用迴圈,直到條件值為1或true。

例如,列表包含節點29、34、43、56和88,則輸出將是交替節點,例如29、43和88。

示例

Input: 29->34->43->56->88
Output: 29 43 88

方法是遍歷整個列表直到最後一個節點。同時,可以使用一個計數器變數,當計數器為偶數或奇數時(取決於使用者的選擇),將其遞增1並列印其值。如果使用者希望從0開始顯示,則顯示偶數計數器的值,否則顯示奇數計數器的值。

下面的程式碼顯示了所給出演算法的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 alternate(struct node* head)
      Set int count = 0
      Loop While (head != NULL)
      IF count % 2 = 0
         Print head->data
         Set count++
         Set head = head->next
      End
   Step 3 -> Declare Function void push(struct node** header, int newdata)
      Create newnode using malloc function
      Set newnode->data = newdata
      Set newnode->next = (*header)
      set (*header) = newnode
   step 4 -> In Main()
      create head pointing to first node using struct node* head = NULL
      Call alternate(head)
STOP

示例

#include <stdio.h>
#include <stdlib.h>
//creating structure of a node
struct node {
   int data;
   struct node* next;
};
//function to find and print alternate node
void alternate(struct node* head) {
   int count = 0;
   while (head != NULL) {
      if (count % 2 == 0)
         printf(" %d ", head->data);
      count++;
      head = head->next;
   }
}
//pushing element into the list
void push(struct node** header, int newdata) {
   struct node* newnode =
   (struct node*)malloc(sizeof(struct node));
   newnode->data = newdata;
   newnode->next = (*header);
   (*header) = newnode;
}
int main() {
   printf("alternate nodes are :");
   struct node* head = NULL;
   push(&head, 1); //calling push function to push elements in list
   push(&head, 9);
   push(&head, 10);
   push(&head, 21);
   push(&head, 80);
   alternate(head);
   return 0;
}

輸出

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

alternate nodes are : 80 10 1

更新於:2019年8月22日

963 次瀏覽

開啟你的職業生涯

完成課程獲得認證

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