线性表—— jmu-ds-单链表的基本运算

实现单链表的基本运算:初始化、插入、删除、求表的长度、判空、释放。
(1)初始化单链表L,输出L->next的值;
(2)依次采用尾插法插入元素:输入分两行数据,第一行是尾插法需要插入的字符数据的个数,第二行是具体插入的字符数据。
(3)输出单链表L;
(4)输出单链表L的长度;
(5)判断单链表L是否为空;
(6)输出单链表L的第3个元素;
(7)输出元素a的位置;
(8)在第4个元素位置上插入‘x’元素;
(9)输出单链表L;
(10)删除L的第3个元素;
(11)输出单链表L;
(12)释放单链表L。

输入格式:
两行数据,第一行是尾插法需要插入的字符数据的个数,第二行是具体插入的字符数据。

输出格式:
按照题目要求输出

输入样例:
5
a b c d e

输出样例:
0
a b c d e
5
no
c
1
a b c x d e
a b x d e

#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
#include <malloc.h>
#include <math.h>
using namespace std;

typedef char ElemType;
typedef struct LNode{
    ElemType data;
    LNode *next;
}LNode, *Linklist;

void Init(Linklist &L)
{
    LNode *tmp;
    tmp = (Linklist)malloc(sizeof(LNode));
    tmp->next = NULL;
    //printf("11111111111\n", tmp->next);
    L = tmp;
}
void Insert(Linklist &L)
{
    int n;
    char c;
    scanf("%d", &n);
    LNode *tmp, *p;
    tmp=L;
    //getchar();
    for(int i = 0; i < n; ++i)
    {
        getchar();
        p = (Linklist)malloc(sizeof(LNode));
        scanf("%c", &p->data);
        p->next = NULL;
        tmp->next = p;
        tmp = p;
    }
}
void print(Linklist L)
{
    int flag = 0;
    LNode *tmp = L->next;
    while(tmp != NULL)
    {
        if(flag) printf(" ");
        flag = 1;
        printf("%c", tmp->data);
        tmp = tmp->next;
    }
    printf("\n");
}
int count(Linklist L)
{
    LNode *tmp = L;
    int cnt = 0;
    while(tmp->next != NULL)
    {
        tmp = tmp->next;
        cnt++;
    }
    return cnt;
}
void printCount(Linklist L, int n)
{
    LNode *tmp = L;
    for(int cnt = 0; cnt < n; ++cnt)
    {
        tmp = tmp->next;
    }
    printf("%c\n", tmp->data);
}
void Locate(Linklist &L, char c)
{
    int cnt = 1;
    LNode *tmp = L->next;
    while(tmp->data != c)
    {
        tmp = tmp->next;
        cnt++;
    }
    printf("%d\n", cnt);
}
void Insert(Linklist &L, char c, int loc)
{
    LNode *tmp = L;
    LNode *p = (Linklist)malloc(sizeof(LNode));
    for(int i = 1; i < loc; ++i)
        tmp = tmp->next;
    p->next = tmp->next;
    p->data = c;
    tmp->next = p;
}
void deleteLoc(Linklist &L, int cnt)
{
    LNode *tmp = L, *p;
    for(int i = 1; i < cnt; ++i)
        tmp = tmp->next;
    p = tmp->next;
    tmp->next = p->next;
    free(p);
}
void release(Linklist &L)
{
    LNode *tmp = L, *p;
    while(tmp != NULL)
    {
        p = tmp;
        tmp = tmp->next;
        free(p);
    }
}
int main()
{
    Linklist L;
    Init(L);
    printf("%d\n", L->next);
    Insert(L);
    print(L);
    printf("%d\n", count(L));
    if(count(L)) printf("no\n");
    else printf("yes\n");
    printCount(L, 3);
    Locate(L, 'a');
    Insert(L, 'x', 4);
    print(L);
    deleteLoc(L, 3);
    print(L);
    release(L);
}

猜你喜欢

转载自blog.csdn.net/weixin_42618424/article/details/85042267
今日推荐