用头插法(或尾插法〉建立带头结点的单链表,对己建立的单链表实现插人、删除、查找和遍历等基本操作的代码
时间: 2024-09-27 11:14:06 浏览: 45
create_linklist_head.rar_Create_LinkList c++_head_头插法
好的,下面是用头插法建立带头结点的单链表,并实现插入、删除、查找和遍历等基本操作的代码:
```c++
#include <iostream>
using namespace std;
// 定义单链表结点
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
// 建立带头结点的单链表
ListNode* createList() {
ListNode* head = new ListNode(0); // 头结点
ListNode* p = head;
int x;
while (cin >> x) {
ListNode* node = new ListNode(x);
p->next = node;
p = p->next;
}
return head;
}
// 插入结点
void insertNode(ListNode* head, int val) {
ListNode* node = new ListNode(val);
node->next = head->next;
head->next = node;
}
// 删除结点
void deleteNode(ListNode* head, int val) {
ListNode* p = head->next;
ListNode* pre = head;
while (p != NULL) {
if (p->val == val) {
pre->next = p->next;
delete p;
break;
}
pre = p;
p = p->next;
}
}
// 查找结点
ListNode* findNode(ListNode* head, int val) {
ListNode* p = head->next;
while (p != NULL) {
if (p->val == val) {
return p;
}
p = p->next;
}
return NULL;
}
// 遍历链表
void traverseList(ListNode* head) {
ListNode* p = head->next;
while (p != NULL) {
cout << p->val << " ";
p = p->next;
}
cout << endl;
}
int main() {
ListNode* head = createList();
traverseList(head);
insertNode(head, 5);
traverseList(head);
deleteNode(head, 3);
traverseList(head);
ListNode* node = findNode(head, 2);
if (node != NULL) {
cout << "Found node: " << node->val << endl;
} else {
cout << "Node not found." << endl;
}
return 0;
}
```
阅读全文