数据结构-编程实现一个单链表的测长
生活随笔
收集整理的這篇文章主要介紹了
数据结构-编程实现一个单链表的测长
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1:代碼如下:
// ConsoleApplication15.cpp : 定義控制臺應用程序的入口點。 // #include "stdafx.h" #include <malloc.h>typedef struct node//定義鏈表結構體 {int data;//節點內容node *next;//指向結構體的指針,下一個節點 }node;node *create()//創建單鏈表 {int i = 0;//鏈表中數據的個數node *head, *p, *q;//這些的本質是節點的地址int x = 0;head = NULL;q = NULL;//初始化q,q代表末節點p = NULL;while (1){printf("please input the data:");scanf_s("%d", &x);if (x == 0)break;//data為0時創建結束p = (node *)malloc(sizeof(node));//用于每次輸入鏈表的數據p->data = x;if (++i == 1)//鏈表頭的指針指向下一個節點 {head = p;q = p;}else{q->next = p;//連接到鏈表尾端q = p;}q->next = NULL;/*尾結點的后繼指針為NULL(空)*/}return head; }int length(node *head) {int len = 0;node *p;p = head->next;while (p != NULL){len++;p = p->next;}return len; }void print(node *head) {node *p;p = head;while (p)/*直到結點q為NULL結束循環*/{printf("%d ", p->data);/*輸出結點中的值*/p = p->next;/*指向下一個結點*/} }int main() {node *head = create();//創建單鏈表printf("Length:%d\n", length(head));print(head);return 0; } View Code運行結果:
轉載于:https://www.cnblogs.com/lovemi93/p/7581520.html
總結
以上是生活随笔為你收集整理的数据结构-编程实现一个单链表的测长的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 洛谷 P2738 [USACO4.1]篱
- 下一篇: 结构(struct)