Description
输入3 4 5 6 7 9999一串整数,9999代表结束,通过尾插法新建链表,查找第二个位置的值并输出,在2个位置插入99,输出为 3 99 4 5 6 7,删除第4个位置的值,打印输出为 3 99 4 5 6 7。
输出函数如下:
void PrintList(LinkList L)
{
L = L->next;
while (L != NULL)
{
printf("%3d", L->data);//打印当前结点数据
L = L->next;//指向下一个结点
}
printf("\n");
}
针对双向链表,有时间的同学自己练习即可,这道题同样也可以用双向链表来实现一遍
Input
输入是3 4 5 6 7 9999
Output
输出是
4
3 99 4 5 6 7
3 99 4 6 7
Sample Input 1
3 4 5 6 7 9999
Sample Output 1
4 3 99 4 5 6 7 3 99 4 6 7
Sample Input 2
1 3 5 7 9 9999
Sample Output 2
3 1 99 3 5 7 9 1 99 3 7 9
#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)
{
L = (LNode*)malloc(sizeof(LNode));
L->next = NULL;
int x; LinkList s;
scanf("%d", &x);
while (x != 9999) {
s = (LNode*)malloc(sizeof(LNode));
s->data = x;
s->next = L->next;
L->next = s;
scanf("%d", &x);
}
return L;
}
void PrintList(LinkList L) {
L = L->next;
while (L!= NULL) {
printf("%3d", L->data);
L = L->next;
}
printf("\n");
}
LinkList CreatList2(LinkList& L) {
L = (LNode*)malloc(sizeof(LNode));
L->next = NULL;
int x; LinkList r, s;
r = L;
scanf("%d", &x);
while (x != 9999) {
s = (LinkList)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;
if (i == 0) {
return L;
}
if (i < 1) {
return NULL;
}
while (p != NULL && j < i) {
p = p->next;
j++;
}
return p;
}
bool DeleteList(LinkList& L, int i) {
LinkList p = GetElem(L, i - 1);
if (p == NULL) {
return false;
}
LinkList q;
q = p->next;
p->next = q->next;
free(q);
q = NULL;
return true;
}
bool ListFrontInsert(LinkList L, int i, ElemType e) {
LinkList p = GetElem(L, i - 1);
if (p == NULL) {
return false;
}
LinkList s;
s = (LinkList)malloc(sizeof(LNode));
s->data = e;
s->next = p->next;
p->next = s;
return true;
}
int main() {
LinkList L;
CreatList2(L);
LinkList p;
p = GetElem(L, 2);
printf("%d\n", p->data);
ListFrontInsert(L, 2, 99);
PrintList(L);
DeleteList(L, 4);
PrintList(L);
}