数据结构::单链表的基本操作
#pragma GCC positionimize(3,"Otrst","inline") //#include "emplace.hpp" #include<bits/stdc++.h> using namespace std; typedef long long ll; const int N=1e6+10; const int INF=0x3f3f3f; const double pi = 3.141592653; const double E = 2.71828182846; const ll mod=1e9+7; const int M=1e3+5; const double eps=1e-8; #define ci(x) scanf("%lld",&x) #define co(x) printf("%lld\n",x) #define InitSize 10 ///带头结点 typedef struct LNode { int data; struct LNode *next; }LNode,*LinkList; bool InitList(LinkList &L) { L=(LNode *)malloc(sizeof(LNode)); if(L==NULL) return false; L->next=NULL; return true; } LNode * GetElem(LinkList L,int i) { if(i<1) return NULL; LNode *p; p = L; //L指向头结点 int j=0; while(p!=NULL&&j<i) { p=p->next; j++; } return p; } LNode * LocateElem(LinkList L,int e) //按值查找 { LNode *p; p=L->next; while(p!=NULL&&p->data!=e) p=p->next; return p; //找到返回p结点 否则返回NULL } int GetLengh(LinkList L) { int len=0; LNode *p=L; while(p->next!=NULL) { p=p->next; len++; } return len; } bool ListNextInsert(LNode *p,int e) //在p节点之后插入新的元素 { if(p==NULL) return false; LNode *s=(LNode *)malloc(sizeof(LNode)); if(s==NULL) return false; s->data=e; s->next=p->next; p->next=s; return true; } bool ListInsert(LinkList &L,int i,int e) // 在第i个位置插入元素e { if(i<=1) return false; LNode *p=GetElem(L,i-1); //找到第i-1个节点 /*if(p==NULL) return false; LNode *s=(LNode *)malloc(sizeof(LNode)); s->data=e; s->next=p->next; p->next=s;//将节点s连到p之后 return true;*/ return ListNextInsert(p,e); } bool ListPriInsert(LNode *p,int e) { if(p==NULL) return false; LNode *s=(LNode *)malloc(sizeof(LNode)); s->next=p->next; p->next=s; s->data=p->data; p->data=e; return true; } bool ListDelet(LinkList &L,int i,int &e)//删除第i个节点 { if(i<=1) return false; /*LNode *p; int j=0; p=L; while(p!=NULL && j<=i-1) { p=p->next; j++; }*/ LNode *p=GetElem(L,i-1); //以上为了找到i-1个节点 if(p==NULL) return false; if(p->next==NULL) return false; LNode *q=p->next; e=q->data; p->next=q->next; free(q); return true; } bool DeletNode(LNode *p) //删除p节点 { if(p==NULL) return false; LNode *q=p->next; p->data=p->next->data; p->next=q->next; free(q); return true; } LinkList List_TailInsert(LinkList &L) //建立后插操作 { L=(LNode *)malloc(sizeof(LNode)); LNode *s,*r=L; int x; while(scanf("%d",&x)!=EOF) { s=(LNode *)malloc(sizeof(LNode)); s->data=x; r->next=s; r=s;//r指向新的表位结点 } r->next=NULL; return L; } LinkList List_HeadInsert(LinkList &L)//逆向建立单链表 { L=(LinkList)malloc(sizeof(LNode)); LNode *s; int x; L->next=NULL; while(scanf("%d",&x)!=EOF) { s=(LNode *)malloc(sizeof(LNode)); s->data=x; s->next=L->next; L->next=s; } return L; } int main() { LinkList L; InitList(L); //头插法 //尾插法 return 0; }