链表
学了那么久的数据结构,,,,,
其实什么都没有,就一句话,无他,唯手熟尔;
//链表的各种实现
// 要时常注意定义临时的链表
//链表的各种实现
// 要时常注意定义临时的链表
#include <cstdio>
#include <cstdlib>
#define true 1
#define false 0
//#define _OJ_
typedef struct Lnode
{
int data;
struct Lnode *next;
} Lnode, *Linklist;
Linklist
InitList(Linklist L, int n)
//正序创建链表
{
int i;
Linklist p, head;
L = (Linklist) malloc (sizeof(Lnode));
head = L;
for(i = 0;i < n; i++) {
p = (Linklist) malloc (sizeof(Lnode));
scanf("%d", &p->data);
L->next = p;
L = p;
}
L->next = NULL;
return head;
}
int
ListEmpty(Linklist L)
//判断此链表是否为空
{
if(L->next == NULL)
return false;
else
return true;
}
int
ListLength(Linklist L)
//计算链表的长度
{
int Len = 0;
while (L->next != NULL)
{
Len++;
L = L->next;
}
return Len;
}
int
Getelem(Linklist L, int i)
//返回第i个元素
{
int cnt = 0;
Linklist p;
p = L;
while (cnt < i) {
p = p->next;
cnt++;
}
return p->data;
}
void
print(Linklist L)
//打印输出每个值
{
Linklist p;
p = L;
while (L->next != NULL) {
printf("%d\n", L->next->data);
L = L->next;
}
}
Linklist
findprevious(Linklist L,int x)
//找到前驱
{
Linklist p;
p = L;
while (p != NULL && p->data != x) {
p = p->next;
}
return p;
}
/*void
Listdelete(Linklist L)
{
Linklist p;
p = L;
p->next = p->next->next;
}*/
Listdelete(Linklist L, int x)
//链表的删除
{
Linklist p, Tmpcell;
p = findprevious(L,x);
if(p->next != NULL)
{
Tmpcell = p->next;
p->next = Tmpcell->next;
free(Tmpcell);
}
}
void
Listinsert(Linklist L,int e)
{
Linklist p, p1;
p = L;
p1 = (Linklist) malloc (sizeof(Lnode));
p1->data = e;
p1->next = p->next;
p->next = p1;
}
void
List_union(Linklist L,Linklist L1,Linklist L2)
//合并链表
{
Linklist p, p1, pc;
p = L->next; p1 = L1->next; pc = L2;
while (p && p1) {
if(p->data <= p1->data)
{pc->next = p; pc = p; p = p->next;}
else{
pc->next = p1; pc = p1; p1 = p1->next;
}
pc->next = p ? p : p1;
}
}
int main(int argc, char const *argv[]) {
#ifndef _OJ_ //ONLINE_JUDGE
freopen("input.txt", "r", stdin);
#endif
int n, i;
int status, Length, elem;
Linklist L;
scanf("%d", &n);
L = InitList(L,n);
status = ListEmpty(L);
printf("status = %d\n", status);
Length = ListLength(L);
printf("Length = %d\n", Length);
scanf("%d", &i);
elem = Getelem(L,i);
printf("elem = %d\n", elem);
print(L);
printf("%d\n", L->next->data);
Listdelete(L);
printf("%d\n", L->next->data);
return 0;
}