当前位置: 代码迷 >> 综合 >> PTA 7-3 jmu-ds-单链表的基本运算
  详细解决方案

PTA 7-3 jmu-ds-单链表的基本运算

热度:76   发布时间:2024-01-18 18:25:30.0
7-3 jmu-ds-单链表的基本运算(15 分)

实现单链表的基本运算:初始化、插入、删除、求表的长度、判空、释放。
(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 <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;#define MASIZE 100typedef struct LNode
{char data;struct LNode *next;
}LNode,*LinkList;void ListCreat(LinkList &L)//初始化单链表
{L=(LNode*)malloc(sizeof(LNode));L->next=NULL;cout<<0<<endl;
}void ListInsert(LinkList &L,int n)//插入数据
{LNode *cur,*rear;rear=L;for(int i=0;i<n;i++){cur=(LNode*)malloc(sizeof(LNode));scanf("%c",&cur->data);cur->next=NULL;rear->next=cur;rear=cur;}
}void Linsert(LinkList L,char a,int i)
{LNode *p;p=L;i--;while(i--){p=p->next;}LNode *q;q=(LNode*)malloc(sizeof(LNode));q->data=a;q->next=p->next;p->next=q;
}void Delete(LinkList &L,int i)//删除某个链表元素
{LNode *p=L,*q;i--;while(i--){p=p->next;}q=(LNode*)malloc(sizeof(LNode));q=p->next->next;p->next=q;
}int LengthList(LinkList &L)//求链表的长度
{LNode *p;int length=0;p=L->next;while(p){length++;p=p->next;}cout<<length<<endl;
}void IsEmptyList(LinkList L)//判断链表是否为空
{if(L->next)cout<<"no"<<endl;elsecout<<"yes"<<endl;
}void PrintList(LinkList L)//输出链表元素
{LNode *p;p=L->next;cout<<p->data;p=p->next;while(p){cout<<" "<<p->data;p=p->next;}cout<<endl;
}void Print(LinkList L,int i)
{LNode *p;p=L;while(i--){p=p->next;}cout<<p->data<<endl;
}void LPrint(LinkList L,char a)//输出某元素的位置
{LNode *p;p=L->next;int length=0;while(p){length++;if(p->data==a){cout<<length<<endl;break;}p=p->next;}
}int main()
{int n;LinkList L;cin>>n;ListCreat(L);ListInsert(L,n);PrintList(L);LengthList(L);IsEmptyList(L);Print(L,3);LPrint(L,'a');Linsert(L,'x',4);PrintList(L);Delete(L,3);PrintList(L);free(L);return 0;
}

  相关解决方案