王道oj/problem18

2022/4/14 6:20:02

本文主要是介绍王道oj/problem18,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

网址:略

思路:见注释;有bug:插入时1和2的结果正好相反,稍后编辑。

代码:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

typedef int ElemType;
typedef struct LNode {
ElemType data;
struct LNode* next;//指向下一个结点
} LNode,*LinkList;
//头插法新建链表
LinkList CreatList1(LinkList& L)//list_head_insert
{
LinkList s; int x;
L = (LinkList)malloc(sizeof(LNode));//带头结点的链表,指针就是存地址的一个空间
L->next = NULL;
scanf("%d", &x);
while (x!= 9999) {
s = (LinkList)malloc(sizeof(LNode));//申请一个新空间s,强制类型转换
s->data = x;//把读到的值,给新空间中的data
s->next = L->next;
L->next = s;
scanf("%d", &x);
}
return L;
}
//尾插法
LinkList CreatList2(LinkList& L)//list_tail_insert
{
int x;
L = (LinkList)malloc(sizeof(LNode));
LNode* s, * r = L;//LinkList s,r = L;也可以
//s代表新结点,r代表表尾结点
scanf("%d", &x);
while (x!= 9999)
{
s = (LNode*)malloc(sizeof(LNode));
s->data = x;
r->next = s;
r = s;
scanf("%d", &x);
}
r->next = NULL;
return L;
}
//查找结点的值
LNode* GetElem(LinkList L, int i)
{
int j = 1;
LNode* p = L->next;//让p指向第一个节点
if (i == 1)
return L;
if (i < 0)
return NULL;
while (p && j < i)
{
p = p->next;
j++;
}
return p;
}
//查找链表中是否有此值
LNode* LocateElem(LinkList L, int e)
{
LinkList p = L->next;
while (p && p->data != e)
{
p = p->next;
}
return p;
}
//往第i个位置插入元素
bool ListFrontInsert(LinkList L, int i, ElemType e)
{
LinkList p = GetElem(L,i - 1);
if (NULL == p)
{
return false;
}
LinkList s = (LNode *)malloc(sizeof(LNode));
s->data = e;
s->next = p->next;
p->next = s;
return true;
}//插入有点问题,插入1和2颠倒了?

//删除指定位置的元素
bool ListDelete(LinkList L, int i)
{
LinkList p = GetElem(L, i - 1);
if (NULL == p)
return false;
LinkList q = p->next;
p->next = q->next;
free(q);
q = NULL;
return true;
}


void PrintList(LinkList L)//打印链表
{
L = L->next;
while (L != NULL)
{
printf("%3d", L->data);
L = L->next;
}
printf("\n");
}

int main()
{
LinkList L;//链表头,是结构体指针类型
LinkList search;//用来存储得到的某一个节点
CreatList2(L);
search = GetElem(L, 2);
if (search != NULL)
{
printf("%d\n", search->data);
}
ListFrontInsert(L, 1, 99);
PrintList(L);
ListDelete(L, 4);
PrintList(L);
return 0;
}



这篇关于王道oj/problem18的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程