數據結構-編程實現一個單鏈表節點的查找


1:代碼如下:

// ConsoleApplication15.cpp : 定義控制台應用程序的入口點。
//

#include "stdafx.h"
#include <malloc.h>
#include <iostream>
using namespace std;

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;/*指向下一個結點*/
    }
}

node *search_node(node *head, int pos)//查找單鏈表pos位置的節點,返回節點的指針。pos從0開始,0返回head節點
{
    node *p = head->next;
    if (pos < 0)//pos位置不正確
    {
        printf("incorrect position to search node!");//pose位置不正確
        return NULL;
    }
    if (pos == 0)
    {
        return head;
    }
    if (pos == NULL)
    {
        printf("Link is empty!");//鏈表為空
        return NULL;
    }
    while (--pos)
    {
        if ((p = p->next) == NULL)
        {
            printf("incorrect position to search node!");//超出鏈表返回
            break;
        }
    }
    return p;
}

int main()
{
    node *head = create();//創建單鏈表
    printf("Length:%d\n", length(head));//測試鏈表的長度
    print(head);//輸出鏈表
    node *search;
    search = search_node(head, 1);
    cout << "查找鏈表的第2個數為:"<<search->data << endl;//注意數是從0開始的
    return 0;
}
View Code

運行結果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM