链表操作-查找结点

题目描述

设计函数int  locate (struct node * head,char x);,找到以head为头指针的链表中,数据域的值等于x的结点,并返回该结点的序号(即是第几个结点)。

输入

一行包含#的字符串,将以#前的每个字符为数据域的值创建多个结点,并将这些结点,利用尾插法链接成链表。
#后还有一个字符,表示要在链表中查找数据域值为该字符的结点。

输出

所查找到的结点的序号。如果找不到这样的结点,则输出0。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct node {
    char data;
    struct node *next;
};

/**
 * 查找字符在链表中的位置函数
 * @param head 链表头指针
 * @param x 要查找的字符
 * @return 找到的位置(从 0 开始计数),若未找到返回 -1
 */
int locate(struct node *head, char x) {
    struct node *p = head;  // 定义指针指向链表头
    int position = 0;  // 记录位置
    while (p!= NULL) {  // 当指针不为空,即链表未遍历完
        if (p->data == x) {  // 如果找到字符
            return position;  // 返回位置
        }
        p = p->next;  // 指针移动到下一个节点
        position++;  // 位置加 1
    }
    return -1;  // 未找到返回 -1
}

/**
 * 销毁链表函数
 * @param head 链表头指针
 */
void destroy(struct node* head) {   
    struct node *p;  // 定义临时指针
    while (head!= NULL) {  // 当链表头不为空
        p = head;  // 临时指针指向链表头
        head = head->next;  // 链表头移动到下一个节点
        free(p);  // 释放临时指针所指节点的内存
    }
}

/**
 * 尾插法创建链表函数
 * @return 创建好的链表头指针
 */
struct node* tailinsert() {  
    struct node *head = NULL;  // 初始化链表头为空
    struct node *tail = NULL;  // 初始化尾指针为空
    char a[100];  // 用于存储输入字符串
    gets(a);  // 获取输入字符串

    for (int i = 0; i < strlen(a); i++) {  // 遍历字符串
        struct node *newNode = (struct node*)malloc(sizeof(struct node));  // 创建新节点
        newNode->data = a[i];  // 设置节点数据
        newNode->next = NULL;  // 设置节点下一个指针为空

        if (head == NULL) {  // 如果链表头为空
            head = newNode;  // 当前节点作为链表头
            tail = newNode;  // 当前节点也作为尾节点
        } else {  // 链表头不为空
            tail->next = newNode;  // 将新节点添加到尾节点后面
            tail = newNode;  // 更新尾节点
        }
    }

    return head;  // 返回链表头指针
}

int main() {
    char c;
    struct node *head;
    head = tailinsert();  // 调用尾插法创建链表函数得到链表头
    c = getchar();  // 获取一个字符输入
    printf("%d", locate(head, c));  // 输出查找该字符的位置结果
    destroy(head);  // 销毁链表
    return 0;
}
  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值