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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP