解题思路:
注意事项:
参考代码:
#include "stdio.h"
#include<stdlib.h>
typedef int Elemtype;
typedef struct LNode //结构定义
{
Elemtype data;
struct LNode* next;
}LNode, *LinkList;
void create_H(LinkList &L) //头插法建立单链表(逆序)
{
printf("INPUT:");
L = (LinkList)malloc(sizeof(LNode));
L->next = NULL;
LNode* s;
int x;
scanf("%d", &x);
while (x!=9999)
{
s = (LNode*)malloc(sizeof(LNode));
s->data = x;
s->next = L->next;
L->next = s;
scanf("%d", &x);
}
}
void create_R(LinkList& L) //尾插法建立单链表(顺序)
{
//printf("INPUT:");
int n; scanf("%d", &n);
L = (LinkList)malloc(sizeof(LNode));
L->next = NULL;
LNode* s,*r=L;
int x;
int j = 0;
//scanf("%d", &x);
while (j<n)
{
scanf("%d", &x); j++;
s = (LNode*)malloc(sizeof(LNode));
s->data = x;
r->next = s;
r = s;
}
r->next = NULL;
}
void printf_L(LinkList L)//打印单链表
{
LNode* p; p = L;
//printf("单链表为:");
while (p->next != NULL)
{
p = p->next;
printf("%d ", p->data);
}
printf("\n");
}
Elemtype getelem(LinkList L, int i) //按序号查找
{
LNode* p; p = L;
int j = 0;
while (p!= NULL && j <i)
{
p = p->next; j++;
}
//printf("%d", p->data);
return p->data;
}
int Locate_L(LinkList L, Elemtype e) //按值查找
{
LNode* p; p = L;
int j = 0;
while (p->data != e && p != NULL)
{
p = p->next;
j++;
}
//if () { return 999; }
return j;
}
int length(LinkList L) //单链表长度
{
LNode* p; p = L;
int j = 0;
while (p->next != NULL)
{
p = p->next;
j++;
}
return j;
}
void Delete_L(LinkList& L, int i) //删除给定序号节点
{
LNode* p; p = L;
int j = 0;
while (p != NULL && j < i - 1) //找到i-1个节点
{
p = p->next; j++;
}
LNode* q; q = p->next;
p->next = q->next;
free(q);
}
void Insert_L(LinkList& L, int i,Elemtype e) //第i个位置插入e
{
LNode* p; p = L;
int j = 0;
LNode* s;
s = (LNode*)malloc(sizeof(LNode));
s->data = e;
while (p != NULL && j < i - 1) //找到i-1个节点
{
p = p->next;
j++;
}
s->next = p->next;
p->next = s;
}
int A(LinkList L, Elemtype e)
{
LNode* p; p = L;
int j = 0;
while (p!=NULL)
{
if (p->data == e) { return 1; }
p = p->next;
}
return 0;
}
int main()
{
LinkList L;
create_R(L);//printf_L(L);
//printf_L(L);
//Insert_L(L, 1, 1); Insert_L(L, 1, 2); Insert_L(L, 1, 3); Insert_L(L, 1, 4); Insert_L(L, 1, 5);
//printf("序号查找的值为:%d\n", getelem(L,4));
//printf("长度:%d\n", length(L));
//printf("值查找的序号为:%d\n", Locate_L(L, 4));
//Delete_L(L, 3);
//Insert_L(L, 3, 999);
int n; scanf("%d", &n);
//printf("%d",Locate_L(L, 6));
while(1)
{
int x;
x = Locate_L(L, n); //if (x==0) {printf_L(L); }
Delete_L(L, x);
//printf_L(L);
if (A(L, n) == 0) { break; }
//break;
}
printf_L(L);
//printf("hfhgfhg");
}
0.0分
0 人评分