(JohnZero)C++:链表


https://blog.csdn.net/liujian20150808/article/details/50640979?locationNum=4&fps=1

LinkList类

//C++形式的链表的插入,遍历输出,链表倒序等操作
#include<iostream>
#include<cstdlib>
using namespace std;
//节点类
struct ListNode {
public:
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(NULL) {}
};
//链表类
class LinkList {
public:
    LinkList() {
        head = NULL;
    }
    void insert(ListNode* node, int position);
    void output();
    void reverse();
private:
    ListNode* head;
};

void LinkList::insert(ListNode* node, int position) {
    if (head == NULL) {
        head = node;
        return;
    }
    if (position == 0) {
        node->next = head;
        head = node;
        return;
    }
    ListNode* currentNode = head;
    int i = 0;
    while (currentNode->next != NULL && i < position - 1) {
        currentNode = currentNode->next;
        i++;
    }
    if (i == position - 1) {
        node->next = currentNode->next;
        currentNode->next = node;
    }
}

void LinkList::output() {
    if (head == NULL) {
        return;
    }
    ListNode* currentNode = head;
    while (currentNode != NULL) {
        cout << currentNode->val << " ";
        currentNode = currentNode->next;
    }
    cout << endl;
}

void LinkList::reverse() {
    if (head == NULL) {
        return;
    }
    ListNode* currentNode = head->next, * nextNode;
    head->next = NULL;
    while (currentNode != NULL) {
        nextNode = currentNode->next;
        currentNode->next = head;
        head = currentNode;
        currentNode = nextNode;
    }
}

int main() {
    LinkList linkList;
    for (int i = 0; i < 10; i++) {
        ListNode* node = new ListNode(i);
        linkList.insert(node, i);
    }
    linkList.output();
    linkList.reverse();
    linkList.output();
    return 0;
}

在这里插入图片描述

用vector初始化链表

struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(NULL) {}
};

vector<int>vec = { 1,2,3,4,5 };
ListNode* head = new ListNode(vec.front());
ListNode* node = head;
for (int i = 1; i < vec.size(); i++)
{
    node->next = new ListNode(vec[i]);
    node = node->next;
}
//for (int i = 0; i < vec.size(); i++)
//{
//    cout << head->val << ' ';
//    head = head->next;
//}
node = head;
while (node != NULL)
{
    cout << node->val << ' ';
    node = node->next;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值