|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include <cstddef>
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
typedef int elemtype;
typedef struct linklist {
elemtype data;
struct linklist* link;
}linknode;
linknode* createlist();
linknode* createfirst(linknode* first);
linknode createlast(linknode* first);
void printlist(linknode* first);
int getlen(linknode* first);
#include"标头.h"
linknode* createlist()
{
elemtype ch;
linknode* first = new linknode;
first->link = NULL;
if (first != NULL) {
return first;
}
else {
printf("分配空间失败!");
}
}
//前插法(createfirst)
linknode* createfirst(linknode* first)
{
elemtype ch;
linknode* newnode;
//linknode* first = new linknode;
first->link = NULL;
while ((ch = getchar() != '\n')) {
newnode = new linknode;
newnode->data = ch;
newnode->link = first->link;
first->link = newnode;
}
return first;
}
//后插法(createlast)
linknode createlast(linknode* first)
{
elemtype ch;
linknode* newnodel;
linknode* r = first;//r指向表尾
//linknode* first = new linknode;
while ((ch = getchar() != '\n')) {
newnodel = new linknode;
newnodel->data = ch;
r->link = newnodel;
r = newnodel; //插入到链表末端,易错
}
return *first;
}
void printlist(linknode* first) {
linknode* p = first->link;
while (p != NULL) {
printf("%d", p->data);
p = p->link;//一直打印到p指向为空
}
printf("\n");
}
int getlen(linknode* first) {
linknode* p = first->link;
int k = 0;
while (p != NULL)
{
k++;
p = p->link;
}
return k;
}
#include "linklist.h"
int main() {
int a, i;
elem_type n, x, ch;
linknode* first = initlist();
printf("请按顺序输入链表元素,中间按空格隔开:\n");
inpulist(first);
while (1) {
printf("请选择下列操作:\n1.打印表中元素\n2.获取链表长度\n3.查找元素位置\n4.插入元素\n5.删除元素\n6.清空链表\n");
scanf("%d", &a);
if (a == 1) {
printf("表中元素如下:\n");
printlist(first);
}
else if (a == 2) {
printf("链表长度为:%d\n", getlen(first));
}
else if (a == 3) {
printf("请输入要查找的元素:\n");
ch = getchar();
scanf("%c", &n);
if (checklist(first, n)) {
printf("元素位于第%d个\n", checklist(first, n));
}
else {
printf("元素不存在!\n");
}
}
else if (a == 4) {
printf("请输入要插入的元素及其位置:\n");
ch = getchar();
scanf("%c %d", &n, &i);
if (insertlist(first, n, i) != 0) {
printf("插入成功!\n");
}
else {
printf("非法位置!\n");
}
}
else if (a == 5) {
printf("请输入要删除元素的位置:\n");
scanf("%d", &i);
if (delelist(first, i, x) != 0) {
printf("删除成功,删除的元素值为:%c\n", x);
}
else {
printf("非法位置!\n");
}
}
else if (a == 6) {
free(first);
printf("链表空间已释放!");
break;
}
else {
printf("非法指令!\n");
}
}
return 0;
}
|
|