1. 程式人生 > >數據結構-編程實現一個單鏈表的測長

數據結構-編程實現一個單鏈表的測長

.com 元素 頭結點 png 指針 控制 data amp 技術分享

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 = (node *)malloc
(sizeof(node));//創建頭結點 q = head;//初始化q,q代表末節點 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
->next = p;//鏈表只有一個元素連接到head的後面 } else { q->next = p;//連接到鏈表尾端 } q = p;//q指向末節點 } q->next = NULL; return head; } int length(node *head) { int len = 0; node *p; p = head->next; while(p!=NULL) { len++; p
= p->next; } return len; } int main() { node *head = create();//創建單鏈表 printf("Length:%d\n", length(head)); return 0; }

運行結果:

技術分享

數據結構-編程實現一個單鏈表的測長