链表的代码
时间: 2023-07-03 15:27:59 浏览: 49
链表是一种常见的数据结构,它由一系列节点组成,每个节点包括两个部分:数据和指向下一个节点的指针。链表的代码实现如下:
```
// 定义链表节点结构体
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
// 定义链表类
class LinkedList {
public:
LinkedList() {
head = NULL;
}
// 在链表末尾添加一个节点
void append(int val) {
ListNode* new_node = new ListNode(val);
if (head == NULL) {
head = new_node;
} else {
ListNode* cur = head;
while (cur->next) {
cur = cur->next;
}
cur->next = new_node;
}
}
// 在链表指定位置插入一个节点
void insert(int index, int val) {
ListNode* new_node = new ListNode(val);
if (index == 0) {
new_node->next = head;
head = new_node;
} else {
ListNode* cur = head;
for (int i = 0; i < index - 1; i++) {
cur = cur->next;
}
new_node->next = cur->next;
cur->next = new_node;
}
}
// 删除链表指定位置的节点
void remove(int index) {
if (index == 0) {
ListNode* cur = head;
head = head->next;
delete cur;
} else {
ListNode* cur = head;
for (int i = 0; i < index - 1; i++) {
cur = cur->next;
}
ListNode* del_node = cur->next;
cur->next = del_node->next;
delete del_node;
}
}
// 获取链表指定位置的节点值
int get(int index) {
ListNode* cur = head;
for (int i = 0; i < index; i++) {
cur = cur->next;
}
return cur->val;
}
// 获取链表长度
int length() {
int len = 0;
ListNode* cur = head;
while (cur) {
len++;
cur = cur->next;
}
return len;
}
private:
ListNode* head; // 链表头节点指针
};
```
以上是链表的简单实现,包括了添加节点、插入节点、删除节点、获取节点值和获取链表长度等基本操作。
相关推荐
![h](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)