C++单链表的创建:头插法与尾插法

1.采用头插法创建单链表:

该方法从一个空表开始,生成新结点,并将读取到的数据存放到新结点的数据域中,然后将新结点插入到当前链表的表头。采用头插法创建单链表时,读入数据的顺序与生成单链表的元素顺序是相反的。

LinkList List_HeadInsert(LinkList &L) {
    
    //头插法
    LNode* s; int x;
    L = new LNode;
    L->next = NULL;
    cin >> x;
    while (x != 9999) {
    
    //输入9999表示结束
        s = new LNode;
        s->data = x;
        s->next = L->next;
        L->next = s;
        cin >> x;
    }
    return L;
}
2.采用尾插法创建单链表:

该方法将新结点插入到当前链表的表尾,为此必须增加一个尾指针r,使其始终指向当前链表的尾结点。

LinkList List_TailInsert(LinkList &L) {
    
    //尾插法
    L = new LNode;
    LNode* s,*r=L; int x;
    
    cin >> x;
    while (x != 9999) {
    
    //输入9999表示结束
        s = new LNode;
        s->data = x;
        r->next = s;
        r = s;
        cin >> x;
    }
    r->next = NULL;
    return L;
}
3.运行截图:

头插法:
在这里插入图片描述
尾插法:

在这里插入图片描述

4.完整代码:
#include<bits/stdc++.h>
using namespace std;

typedef struct LNode {
    
    
    int data;
    struct LNode* next;
}LNode,*LinkList;

LinkList List_HeadInsert(LinkList &L) {
    
    //头插法
    LNode* s; int x;
    L = new LNode;
    L->next = NULL;
    cin >> x;
    while (x != 9999) {
    
    //输入9999表示结束
        s = new LNode;
        s->data = x;
        s->next = L->next;
        L->next = s;
        cin >> x;
    }
    return L;
}

LinkList List_TailInsert(LinkList &L) {
    
    //尾插法
    L = new LNode;
    LNode* s,*r=L; int x;
    
    cin >> x;
    while (x != 9999) {
    
    //输入9999表示结束
        s = new LNode;
        s->data = x;
        r->next = s;
        r = s;
        cin >> x;
    }
    r->next = NULL;
    return L;
}

void printk(LinkList& L) {
    
    //输出单链表

    LinkList q;
    q = L->next;
    while (q) {
    
    
        cout<<q->data<<" ";
        q = q->next;
    }
    cout << endl;
}


int main() {
    
    

    LinkList L = new LNode;
    cout << "请选择创建单链表的方法:1.头插法;2.尾插法。"<<endl;

    int n;
    cin >> n;
    
    if (n == 1) {
    
    
        cout << "请输入数据元素,输入9999结束输入:" << endl;
        L = List_HeadInsert(L);
        cout << "头插法创建单链表输出结果如下:" << endl;
        printk(L);
    }
    else if (n == 2) {
    
    
        cout << "请输入数据元素,输入9999结束输入" << endl;
        L = List_TailInsert(L);
        cout << "尾插法创建单链表输出结果如下:" << endl;
        printk(L);
    }
    else cout << "请输入正确的指令"<<endl;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43912621/article/details/117479998