标签:
关于链表是最基础的数据结构,,在此不再多说;;;;只贴出一些简单代码!!!!!!!!!!!!!!!!
// 关于数据结构的总结与复习 Coding
// 1.线性表
#include <cstdio>
#include <cstdlib>
#define ok 1
#define error 0
//#define _OJ_
typedef struct Lnode
{
int data;
struct Lnode *next;
} Lnode, *Linklist;
Linklist
Init_List(void)
//对链表的建立采用正序的方式插入
{
int i, n;
Linklist L, p, head;
L = (Linklist) malloc (sizeof(Lnode));
head = L;
scanf("%d", &n);
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;
}
Linklist
Merge_List(Linklist La, Linklist Lb)
//对两个链表的合并
{
Linklist Lc, Pa, Pb, Pc;
Lc = (Linklist) malloc (sizeof(Lnode));
Pa = La->next; Pb = Lb->next; Pc = Lc;
printf("合并两个链表:");
while (Pa && Pb) {
if(Pa->data < Pb->data){
Pc->next = Pa; Pc = Pc->next; Pa = Pa->next;
}else{
Pc->next = Pb; Pc = Pc->next; Pb = Pb->next;
}
}
Pc->next = Pa ? Pa : Pb;
return Lc;
}
int
List_Inster(Linklist L, int i, int e)
//向顺序表中插入元素
{
int j = 0;
Linklist p, s;
p = L;
printf("在位置%d插入%d", i, e);
while (p && j < i - 1) { //总是找到此元素的前驱
p = p->next; j++;
}
if(p == NULL && j == 1) {
printf("error\n"); return 0;
}
s = (Linklist) malloc (sizeof(Lnode));
s->data = e; s->next = p->next;
p->next = s;
}
int
List_Delete(Linklist L, int i)
//对链表进行删除操作
{
int j = 0, e;
Linklist p, q;
p = L;
printf("删除第%d个元素 :", i);
while(p->next && j < i - 1) { //前一个节点(前驱)同理j = 1时 j < i
p = p->next; j++;
}
if(p->next == NULL && j == 0) {
printf("error\n"); return 0;
}
q = p->next; p->next = q->next;
e = q->data;
free(q);
return e;
}
void
print(Linklist L)
//打印输出
{
Linklist p;
p = L->next; printf("打印链表 :");
while (p) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main(int argc, char const *argv[]) {
#ifndef _OJ_ //ONLINE JUDGE
freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
#endif
int n;
Linklist L, p, q;
L = Init_List(); p = Init_List();
print(L);
List_Inster(L, 2, 5);
print(L);
List_Delete(L, 3);
print(L);
q = Merge_List(L, p);
print(q);
return 0;
}
---------------------------------------------------------------------------------------
coding --------------------------------
标签:
原文地址:http://www.cnblogs.com/airfand/p/5059164.html