前言
最近终于闲下来了,把之前写的单向链表代码总结上传一下。
头文件
struct Node {
int val;
Node* pNext;
Node(int val) {
this->val = val;
this->pNext = NULL;
}
};
class List {
public:
Node* buildList(int arr[], int n);
void print(Node* head);
bool checkNode(Node* head, int val);
void changeNode(Node* head, int val, int des);
Node* addNode(Node* head, int val , int addVal);
Node* deleteNode(Node* head, int val);
void deleteList(Node* head);
};
cpp文件
#include"list.h"
Node* List::buildList(int arr[], int n) {
Node* head = NULL;
Node* tail = NULL;
for (int i = 0; i < n; i++) {
Node *temp = (Node*)malloc(sizeof(Node));
temp->val = arr[i];
temp->pNext = NULL;
if (head == NULL) {
head = temp;
tail = temp;
}
else {
tail->pNext = temp;
tail = temp;
}
}
return head;
}
void List::print(Node* head) {
while (head) {
cout << head->val << endl;
head = head->pNext;
}
}
bool List::checkNode(Node* head, int val) {
Node* tmp = head;
while (tmp) {
if (tmp->val != val) {
tmp = tmp->pNext;
}
else return true;
}
return false;
}
void List::changeNode(Node* head, int val, int des) {
Node* tmp = head;
while (tmp) {
if (tmp->val == val) {
tmp->val = des;
return;
}
else tmp = tmp->pNext;
}
}
Node* List::addNode(Node* head, int val, int addVal) {
Node* tmp1 = head;
Node* tmp2 = tmp1;
Node* des = (Node*)malloc(sizeof(Node));
des->val = addVal;
des->pNext = NULL;
if (head->val == val) {
des->pNext = head;
head = des;
return head;
}
while (tmp1) {
if (tmp1->val == val) {
tmp2->pNext = des;
des->pNext = tmp1;
return head;
}
else {
tmp2 = tmp1;
tmp1 = tmp1->pNext;
}
}
return head;
}
Node* List::deleteNode(Node* head, int val) {
Node* cur = head;
if (head->val == val) {
head = head->pNext;
}
while (cur->pNext) {
if (cur->pNext->val== val) {
Node* tmp = cur->pNext;
cur->pNext = cur->pNext->pNext;
delete tmp;
return head;
}
cur = cur->pNext;
}
return head;
}
void List::deleteList(Node* head) {
Node* tmp = head;
while (head) {
tmp = head->pNext;
delete head;
head = tmp;
}
}
|