首页 > 代码库 > 线性链表

线性链表

#include<iostream>#include<cstdio>#include<cstring>#include<cstdlib>#include<cmath>#include<cctype>#include<queue>#include<vector>#include<algorithm>#define N 1001000#define INf 0X3f3f3f3fusing namespace std;typedef long long LL;#define MAXSIZE 100#define OK 1#define ERROR 0#define OVERFLOW -2#define TRUE 1#define FALSE 0typedef int ElemType;typedef int Status;typedef struct node{    ElemType data;    struct node *next;} LNode, *LinkList;int m=sizeof(LNode);Status GetElem_L(LinkList L, int i, ElemType &e){    LinkList p=L->next;    int j=1;    while(j<i&&p)    {        p=p->next;        j++;    }    if(!p)        return ERROR;    e=p->data;    return OK;}void TravelList_L(LinkList L){    LinkList p=L->next;    while(p)    {        printf("%d ", p->data);        p=p->next;    }}void CreateList_L(LinkList &L, int n){    L=(LinkList)malloc(m);    L->next=NULL;    for(int i=0; i<n; i++)    {        LinkList p=(LinkList)malloc(m);        scanf("%d", &(p->data));        p->next=L->next;        L->next=p;    }}Status InsertList_L(LinkList &L, int i, ElemType e){    printf("请按所给思路实现单链表插入运算!\n");    LinkList s, p=L;    int j=0;    while(!p&&j!=i-1)    {        p=p->next;        j++;    }    if(!p || i<1)        return ERROR;    s=(LinkList)malloc(m);    s->data=http://www.mamicode.com/e;    s->next=p->next;    p->next=s;    return OK;}Status DeleteList_L(LinkList &L, int i, int &e){    printf("请按所给思路实现单链表删除运算!\n");    LinkList p=L, q;    int j=0;    while(p&&j!=i-1)    {        p=p->next;        j++;    }    if(!p || i<1)        return ERROR;    q=p->next;    e=q->data;    p->next=q->next;    free(q);    return OK;}int main(){    LinkList L1;    int n;    ElemType x;    printf("请输一个整数:");    scanf("%d", &n);    printf("\n尾插法建单链表,请输入%d个整数:\n", n);    CreateList_L(L1, n);    printf("尾插法建单链表成功!,单链表中的数据是:\n");    TravelList_L(L1);    printf("\n");    printf("在第一个结点位置插入元素15:\n");    InsertList_L(L1, 1, 15);    printf("插入后,链表中数据为:\n");    TravelList_L(L1);    printf("\n");    if(DeleteList_L(L1, 3, x))    {        printf("\n删除第三个元素成功!被删除元素是:%d\n删除后单链表中数据是\n", x);        TravelList_L(L1);        printf("\n");    }    else        printf("\n删除元素失败\n");    return 0;}

 

线性链表