递归反转链表改变原链表吗_在不使用递归的情况下找到链表的长度
遞歸反轉鏈表改變原鏈表嗎
Solution:
解:
Algorithm to find length
查找長度的算法
Input:
輸入:
A singly linked list whose address of the first node is stored in a pointer, say head.
一個單鏈表 ,其第一個節點的地址存儲在指針(例如head)中。
Output:
輸出:
The no of nodes in the list, c
列表中的節點數c
Data structure used:
使用的數據結構:
Singly linked list where each node contains a data element say data, and the address of the immediate next node say next, with head holding the address of the first node.
單鏈列表,其中每個節點包含一個數據元素,例如data ,直接下一個節點的地址說next ,頭保持第一個節點的地址。
Pseudo code:
偽代碼:
Begintemp=headc=0 //counter to store count of nodesWhile(temp!=NULL) //upto end of linked listbeginc=c+1temp=temp->nextEnd while EndC code:
C代碼:
#include <stdio.h> #include <stdlib.h>//node sructure typedef struct list {int data;struct list *next; }node;int length(node *temp);int main() {node *head=NULL,*temp,*temp1;int choice,count;//building linked listdo{temp=(node *)malloc(sizeof(node));if(temp!=NULL){printf("\nEnter the element in the list : ");scanf("%d",&temp->data);temp->next=NULL;if(head==NULL){ head=temp;}else{temp1=head;while(temp1->next!=NULL){temp1=temp1->next;}temp1->next=temp;}}else{printf("\nMemory not avilable...node allocation is not possible");}printf("\nIf you wish to add more data on the list enter 1 : ");scanf("%d",&choice);}while(choice==1);//Now counting the length of the list using a user defined functioncount=length(head);printf("\nThe length of the list is : %d",count);return 0; }//function to find length iteratively int length(node *temp) {int c=0;//travarsing to the end of the list and count the number of nodeswhile(temp!=NULL) {c=c+1;temp=temp->next;}return c; }Output
輸出量
Enter the element in the list : 1If you wish to add more data on the list enter 1 : 1Enter the element in the list : 2If you wish to add more data on the list enter 1 : 1Enter the element in the list : 3If you wish to add more data on the list enter 1 : 1Enter the element in the list : 4If you wish to add more data on the list enter 1 : 1Enter the element in the list : 5If you wish to add more data on the list enter 1 : 0The length of the list is : 5翻譯自: https://www.includehelp.com/c-programs/find-the-length-of-a-linked-list-without-using-recursion.aspx
遞歸反轉鏈表改變原鏈表嗎
總結
以上是生活随笔為你收集整理的递归反转链表改变原链表吗_在不使用递归的情况下找到链表的长度的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 将搜索二叉树转换为链表_将给定的二叉树转
- 下一篇: Java LinkedList对象的cl