单链表遍历_单链表及其遍历实现的基本操作
單鏈表遍歷
單鏈表 (Single linked list)
Single linked list contains a number of nodes where each node has a data field and a pointer to next node. The link of the last node is to NULL, indicates end of list.
單個鏈表包含許多節點,其中每個節點都有一個數據字段和一個指向下一個節點的指針。 最后一個節點的鏈接為NULL,表示列表結尾。
單鏈表結構 (Single linked list structure)
The node in the linked list can be created using struct.
可以使用struct創建鏈接列表中的節點。
struct node{// data field, can be of various type, here integerint data; // pointer to next nodestruct node* next; };鏈表上的基本操作 (Basic operations on linked list)
Traversing
遍歷
Inserting node
插入節點
Deleting node
刪除節點
單個鏈表的遍歷技術 (Traversing technique for a single linked list)
Follow the pointers
跟隨指針
Display content of current nodes
顯示當前節點的內容
Stop when next pointer is NULL
當下一個指針為NULL時停止
C代碼遍歷鏈接列表并計算節點數 (C code to traverse a linked list and count number of nodes )
#include <stdio.h> #include <stdlib.h>struct node{int data; // data fieldstruct node *next; };void traverse(struct node* head){struct node* current=head; // current node set to headint count=0; // to count total no of nodesprintf("\n traversing the list\n");//traverse until current node isn't NULLwhile(current!=NULL){ count++; //increase node countprintf("%d ",current->data);current=current->next; // go to next node}printf("\ntotal no of nodes : %d\n",count); }struct node* creatnode(int d){struct node* temp= (struct node*) malloc(sizeof(struct node));temp->data=d;temp->next=NULL;return temp; }int main() {printf("creating & traversing linked list\n");//same linked list is built according to image shownstruct node* head=creatnode(5);head->next=creatnode(10);head->next->next=creatnode(20);head->next->next->next=creatnode(1);traverse(head);return 0; }Output
輸出量
creating & traversing linked listtraversing the list 5 10 20 1 total no of nodes : 4Time complexity:
時間復雜度:
O(n), for scanning the list of size n
O(n) ,用于掃描大小為n的列表
Space complexity:
空間復雜度:
O(1), no additional memory required
O(1) ,不需要額外的內存
翻譯自: https://www.includehelp.com/data-structure-tutorial/single-linked-list-and-its-basic-operations-with-traversing-implementation.aspx
單鏈表遍歷
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的单链表遍历_单链表及其遍历实现的基本操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java Short类hashCode(
- 下一篇: 最小硬币问题_进行更改的最小硬币数量