您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息

单链表的节点乘积

2024/4/27 22:49:19发布6次查看
给定 n 个节点,任务是打印单链表中所有节点的乘积。程序必须从初始节点开始遍历单向链表的所有节点,直到找不到 null。
示例input -: 1 2 3 4 5output -: 120
在上面的例子中,从第一个节点开始遍历所有节点,即 1, 2 3, 4, 5, 6,它们的乘积为 1*2*3*4*5*6 = 120
下面使用的方法如下获取一个临时指针,比如节点类型的 temp将此临时指针设置为头指针指向的第一个节点当 temp 不为 null 时,将 temp 移动到 temp ->next。设置 product=product*(temp->data)算法 h2>startstep 1 -> create structure of a node and temp, next and head as pointer to a structure node struct node int data struct node *next, *head, *temp endstep 2 -> declare function to insert a node in a list void insert(int val) struct node* newnode = (struct node*)malloc(sizeof(struct node)) newnode->data = val if head= null set head = newnode set head->next = null end else set temp=head loop while temp->next!=null set temp=temp->next end set newnode->next=null set temp->next=newnode endstep 3 -> declare a function to display list void display() if head=null print no node end else set temp=head loop while temp!=null print temp->data set temp=temp->next end endstep 4 -> declare a function to find alternate nodes void product_nodes() declare int product=1 set temp=head loop while temp!=null set product=product * (temp->data) set temp=temp->next end print productstep 5 -> in main() create nodes using struct node* head = null; call function insert(10) to insert a node call display() to display the list call product_nodes() to find alternate nodes productstop
示例#include<stdio.h>#include<stdlib.h>//structure of a nodestruct node{ int data; struct node *next;}*head,*temp;//function for inserting nodes into a listvoid insert(int val){ struct node* newnode = (struct node*)malloc(sizeof(struct node)); newnode->data = val; newnode->next = null; if(head == null){ head = newnode; temp = head; } else { temp->next=newnode; temp=temp->next; }}//function for displaying a listvoid display(){ if(head==null) printf("no node "); else{ temp=head; while(temp!=null){ printf("%d ",temp->data); temp=temp->next; } }}//function for finding productvoid product_nodes(){ int product=1; temp=head; while(temp!=null){ product=product * (temp->data); temp=temp->next; } printf("
product of nodes is : %d" ,product);}int main(){ //creating list struct node* head = null; //inserting elements into a list insert(1); insert(2); insert(3); insert(4); insert(5); insert(6); //displaying the list printf("linked list is : "); display(); //calling function for finding prodouct product_nodes(); return 0;}
输出linked list is : 1 2 3 4 5 6product of nodes is : 720
以上就是单链表的节点乘积的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录