- #include <iostream>
- using namespace std;
- #define Status int
- #define ElemType int
- typedef struct LNode
- {
- ElemType data;
- struct LNode *next;
- }LNode,*LinkList;
- Status CreateList_L(LinkList &L,int n)// 头插法逆序输出
- {
- LinkList p;
- L=(LinkList)malloc(sizeof(LNode));
- L->next=NULL;
- for(int i=1;i<=n;i++)//for(int i=n;i>0;--i)
- {
- p=(LinkList)malloc(sizeof(LNode));
- //scanf(&p->data);
- cin>>p->data;
- p->next=L->next;// 头插法
- L->next=p;
- }
- return 1;
- }
- Status BehindCreateList_L(LinkList &L,int n)// 尾插法可得正序输出
- {
- LinkList p;
- L=(LinkList)malloc(sizeof(LNode));
- L->next=NULL;
- LinkList q=L;
- for(int i=1;i<=n;i++)//for(int i=n;i>0;--i)
- {
- p=(LinkList)malloc(sizeof(LNode));
- //scanf(&p->data);
- cin>>p->data;
- p->next=q->next;
- q->next=p;
- q=q->next;
- ///p->next=L->next;// 头插法
- //L->next=p;
- }
- return 1;
- }
- Status ListInsert_L(LinkList &head,int i,ElemType e,int n)// 第 i 个位置之前插入数据
- {
- if(i<0||i>n)
- {
- cout<<"n erroe"<<endl;
- }
- LinkList p;
- LinkList q=head;
- p=(LinkList)malloc(sizeof(LNode));
- int j=0;
- while (q&&j<i-1)//i-1 node
- {
- q=q->next;
- j++;
- }
- if (!p||j>i-1)
- {
- return -1;
- }
- p->data=e;
- p->next=q->next;
- q->next=p;
- return 1;
- }
- Status ShowList_L(LinkList &L)
- {
- LinkList p=L->next;
- while(p)
- {
- cout<<p->data<<endl;
- p=p->next;
- }
- return 1;
- }
- int main ()
- {
- LinkList a;
- //CreateList_L(a,4);
- BehindCreateList_L(a,4);
- ShowList_L(a);
- system("pause");
- }
1LinkList 指向结构体的指针
2LinkList &L 引用链表的首地址, 操作能作用于原链表
3 头插法逆序输出, 尾插法顺序输出
来源: http://www.bubuko.com/infodetail-2807357.html