单链表遍历_单链表及其遍历实现的基本操作
單鏈表遍歷
單鏈表 (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.
單個鏈表包含許多節(jié)點,其中每個節(jié)點都有一個數(shù)據(jù)字段和一個指向下一個節(jié)點的指針。 最后一個節(jié)點的鏈接為NULL,表示列表結(jié)尾。
單鏈表結(jié)構(gòu) (Single linked list structure)
The node in the linked list can be created using struct.
可以使用struct創(chuàng)建鏈接列表中的節(jié)點。
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
插入節(jié)點
Deleting node
刪除節(jié)點
單個鏈表的遍歷技術(shù) (Traversing technique for a single linked list)
Follow the pointers
跟隨指針
Display content of current nodes
顯示當(dāng)前節(jié)點的內(nèi)容
Stop when next pointer is NULL
當(dāng)下一個指針為NULL時停止
C代碼遍歷鏈接列表并計算節(jié)點數(shù) (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:
時間復(fù)雜度:
O(n), for scanning the list of size n
O(n) ,用于掃描大小為n的列表
Space complexity:
空間復(fù)雜度:
O(1), no additional memory required
O(1) ,不需要額外的內(nèi)存
翻譯自: https://www.includehelp.com/data-structure-tutorial/single-linked-list-and-its-basic-operations-with-traversing-implementation.aspx
單鏈表遍歷
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的单链表遍历_单链表及其遍历实现的基本操作的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java Short类hashCode(
- 下一篇: 最小硬币问题_进行更改的最小硬币数量