C++构建链表

代码

头文件

LinkList.h

#ifndef LINKLIST_H
#define LINKLIST_H

#include <iostream>
#include <vector>

class LinkList {
   
	friend std::ostream &operator<<(std::ostream &out, const LinkList &L);
	friend LinkList* link2node2link(LinkList *obj);

public:
    struct ListNode {
   
        int val;
        ListNode *next;
        ListNode() : val(0), next(nullptr) {
   }
        ListNode(int x) : val(x), next(nullptr) {
   }
        ListNode(int x, ListNode* next) : val(x), next(next) {
   }
    };

    LinkList() {
   
        _dummyHead = new ListNode(0);
        _len = 0;
    }
    
	int get(int index) const;				// 取得链表第index个数的值
	void addAtHead(int val);				// 头插法
	void addAtTail(int val);				// 尾插法
	void addAtIndex(int index, int val);	// 在第index个数之后插入
	void deleteAtIndex(int index);			// 删除第index个数
	void reverseList();						// 反转链表

private:
    ListNode *_dummyHead;
    unsigned _len = 0;
};

int LinkList::get(int index) const {
   
    if (index < 0 || index > (_len - 1)) return -1;
    ListNode *cur = _dummyHead->next;
    while (index--) {
   
        cur = cur->next;
    }
    return cur->val;
}

void LinkList::addAtHead(int val) {
   
    ListNode *newNode = new ListNode(val);	// 用val创建新节点
    newNode->next = _dummyHead->next;		
    _dummyHead->next = newNode;
    ++_len
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C语言中的标准模板库(STL)是C++的一部分,不适用于C语言。然而,你可以使用C语言来实现链表和循环链表。 在C语言中,你可以通过定义一个结构体来表示链表的节点,每个节点包含一个数据元素和一个指向下一个节点的指针。下面是一个简单的例子: ```c struct ListNode { int data; struct ListNode* next; }; ``` 要创建一个循环链表,你需要确保最后一个节点的指针指向第一个节点。这样,遍历链表时就可以通过检查指针是否指向第一个节点来判断是否到达链表的末尾。 下面是一个简单的循环链表的示例代码: ```c #include <stdio.h> #include <stdlib.h> struct ListNode { int data; struct ListNode* next; }; void printList(struct ListNode* head) { struct ListNode* current = head; if (head == NULL) { printf("List is empty.\n"); return; } do { printf("%d ", current->data); current = current->next; } while (current != head); printf("\n"); } int main() { struct ListNode* head = NULL; struct ListNode* second = NULL; struct ListNode* third = NULL; // 创建三个节点 head = (struct ListNode*)malloc(sizeof(struct ListNode)); second = (struct ListNode*)malloc(sizeof(struct ListNode)); third = (struct ListNode*)malloc(sizeof(struct ListNode)); // 赋值数据 head->data = 1; second->data = 2; third->data = 3; // 构建循环链表 head->next = second; second->next = third; third->next = head; printList(head); // 释放内存 free(head); free(second); free(third); return 0; } ``` 这个示例代码创建了一个包含3个节点的循环链表,并打印出链表中的元素。注意在释放内存之前,需要对每个节点调用`free`函数进行释放。 希望这个例子对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值