数据结构-编程实现一个单链表节点的查找

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

运行结果:

posted @ 2017-09-26 17:03  一串字符串  阅读(1653)  评论(0编辑  收藏  举报