C++ 头插法建立单链表,单链表原地逆置以及尾插法建立单链表
生活随笔
收集整理的這篇文章主要介紹了
C++ 头插法建立单链表,单链表原地逆置以及尾插法建立单链表
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#include <iostream>
#include <stdlib.h>
#include <cstdio>
typedef int ElemType;
using namespace std;
//單鏈表的結構體
typedef struct LNode
{ElemType data;LNode *next;
}LNode,*LinkList;
//頭插法建立單鏈表
LinkList List_HeadInsert(LinkList &L)
{L=(LNode *)malloc(sizeof(LNode));L->next=NULL;LNode *s;//s為新插入結點的指針int x;scanf("%d",&x);while(x!=9999){s=(LNode *)malloc(sizeof(LNode));//為新結點分配一片內存空間,并將該內存空間的返回地址賦值給ss->data=x;s->next=L->next;//將s插入到頭結點之后L->next=s;scanf("%d",&x);}return L;
}
//尾插法建立單鏈表
LinkList List_TailInsert(LinkList &L)
{L=(LNode *)malloc(sizeof(LNode));L->next=NULL;LNode *s;LNode *r=L;//r為尾指針int x;scanf("%d",&x);while(x!=9999){s=(LNode *)malloc(sizeof(LNode));s->data=x;r->next=s;//將s插入在r之后r=s;//將r向后移動,保證r一直是尾指針scanf("%d",&x);}r->next=NULL;//將尾指針的next置為空,防止其指向其他內存空間return L;
}
//單鏈表的原地逆置
LinkList Reverse(LinkList &L)
{LNode *p=L->next;//用p保存L的next域L->next=NULL;//將L的next域置為空LNode *r;while(p!=NULL){r=p->next;//用r來保存p的next域,防止斷鏈p->next=L->next;//將p插入在L之后L->next=p;p=r;//將p向后移動}return L;
}
//打印輸出單鏈表
ElemType PrintList(LinkList L)
{LNode *p=L->next;while(p!=NULL){cout<<p->data<<" ";p=p->next;}cout<<endl;return 0;
}
int main()
{LinkList L1;//聲明單鏈表cout<<"請輸入單鏈表L1中的數據元素:"<<endl;List_HeadInsert(L1);//頭插法建表cout<<"頭插法建立單鏈表的結果為:"<<endl;PrintList(L1);//打印輸出單鏈表Reverse(L1);//單鏈表原地逆置cout<<"將此單鏈表原地逆置的結果為:"<<endl;PrintList(L1);//打印輸出單鏈表LinkList L2;cout<<"請輸入單鏈表L2中的數據元素:"<<endl;List_TailInsert(L2);cout<<"尾插法建立單鏈表的結果為:"<<endl;PrintList(L2);return 0;
}
總結
以上是生活随笔為你收集整理的C++ 头插法建立单链表,单链表原地逆置以及尾插法建立单链表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 地图绘制和四色算法,图搜索算法,最小生成
- 下一篇: 飞利浦linux视频采集卡,飞利浦saa