单向链表的C++实现

来源:互联网 发布:魔方秀软件下载 编辑:程序博客网 时间:2024/05/18 15:28

最近开始学习数据结构,听了网易Mooc上何钦民老师的课感觉还不错。

线性表是同类型数据元素构成的有序序列的数据结构。本次使用了C++实现单向链表。

在编程过程中发现初始化是个非常常见的问题,在创建新节点和多次重复使用同一变量(临时变量)时要注意初始化成0或NULL

#include <iostream>#include <malloc.h>using namespace std;typedef struct node{    int a;    int n;    node* next;} node;//线性表的节点结构,为两个整形和一个指向下个节点的指针node *linklist;//线性表头指针void create(){    linklist=(node*)(malloc(sizeof(node)));    linklist->next=NULL;    cout<<"initialize successfully"<<endl;}int length(node*l){    int len=0;    while(l->next!=NULL)    {        l=l->next;        len++;    }    return len;}void print(node*L){    int i=0;    while(L!=NULL)    {        if(i!=0)        cout<<L->a<<endl;        L=L->next;        i++;    }}void add(node*l,int ele){    while(l->next!=NULL)    {        l=l->next;    }    node *tmp=(node*)malloc(sizeof(node));    l->next=tmp;    tmp->a=ele;    tmp->next=NULL;//当接上下一个节点时,要对节点的next指针进行初始化。    tmp->n=0;}void insert(int pos,int ele,node*l){    int len=length(l);    if(pos>len)    {        cout<<"illegal position"<<endl;        return;    }    if(pos==len)    {        add(l,ele);        return;    }    while(pos>0)    {        pos--;        l=l->next;    }    node *tmp=(node*)malloc(sizeof(node));    tmp->next=l->next;    l->next=tmp;    tmp->a=ele;    tmp->n=0;}void dele(int pos,node*l){    int len=length(l);    if(pos>=len)    {        cout<<"illegal position"<<endl;        return;    }    while(pos>1)    {        pos--;        l=l->next;    }    node *tmp=l->next;    free(tmp);    l->next=l->next->next;}int main(){    int n;    int ele;    int pos;    cout<<"1--initialize   2--get length  3--add"<<endl;    cout<<"4--print        5--insert      6--delete    0--exit"<<endl;    while(true)    {        cin>>n;        switch (n)        {        case 1:            create();            break;        case 2:            cout<<"length= "<<length(linklist)<<endl;            break;        case 3:            cout<<"please input a number:"<<endl;            cin>>ele;            add(linklist,ele);            break;        case 4:            print(linklist);            break;        case 5:            cin>>pos>>ele;            insert(pos,ele,linklist);            break;        case 6:            cin>>pos;            dele(pos,linklist);            break;        case 0:            return 0;        default:            cout<<"illegal charactor"<<endl;            break;        }    }    return 0;}

多次重复使用同一个变量(可能是临时变量)的时候一定要注意初始化。

0 0
原创粉丝点击