ff…… 2023-09-25 09:01 采纳率: 90.9%
浏览 166
已结题

】编写算法,在带头结点的单链表结构上实现线性表操作

编写算法,在带头结点的单链表结构上实现线性表操作:InitList(),Length(L),Locate(L, x),Insert(L, i, x),Delete(L, i),PrintList(L)。

  • 写回答

2条回答 默认 最新

  • 就如花开时 2023-09-25 09:07
    关注
    
    #include <stdio.h>
    #include <stdlib.h>
    
    // 定义链表节点结构
    typedef struct Node {
        int data;
        struct Node* next;
    } ListNode;
    
    // 初始化链表
    void InitList(ListNode** L) {
        *L = (ListNode*)malloc(sizeof(ListNode));
        (*L)->next = NULL;
    }
    
    // 获取链表长度
    int Length(ListNode* L) {
        int len = 0;
        ListNode* p = L->next;
        while (p != NULL) {
            len++;
            p = p->next;
        }
        return len;
    }
    
    // 在链表中查找元素位置
    int Locate(ListNode* L, int x) {
        int pos = 0;
        ListNode* p = L->next;
        while (p != NULL) {
            pos++;
            if (p->data == x) {
                return pos;
            }
            p = p->next;
        }
        return -1; 
    }
    
    // 在链表指定位置插入元素
    void Insert(ListNode* L, int i, int x) {
        if (i < 1 || i > Length(L) + 1) {
            printf("插入位置非法\n");
            return;
        }
        ListNode* p = L;
        for (int j = 1; j < i; j++) {
            p = p->next;
        }
        ListNode* newNode = (ListNode*)malloc(sizeof(ListNode));
        newNode->data = x;
        newNode->next = p->next;
        p->next = newNode;
    }
    
    // 在链表指定位置删除元素
    void Delete(ListNode* L, int i) {
        if (i < 1 || i > Length(L)) {
            printf("删除位置非法\n");
            return;
        }
        ListNode* p = L;
        for (int j = 1; j < i; j++) {
            p = p->next;
        }
        ListNode* q = p->next;
        p->next = q->next;
        free(q);
    }
    
    // 打印链表
    void PrintList(ListNode* L) {
        ListNode* p = L->next;
        while (p != NULL) {
            printf("%d ", p->data);
            p = p->next;
        }
        printf("\n");
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 10月3日
  • 已采纳回答 9月25日
  • 创建了问题 9月25日