代码有任何可改进或错误请指正
代码
List.h
#pragma once
#include<iostream>
using namespace std;
typedef struct LNode* ListP;
struct LNode {
int Data;
ListP Next;
LNode(int val, ListP Next) :Data(val), Next(NULL) {}
LNode() = default;
};
class cList {
private:
static ListP pHead;
static ListP pTail;
public:
ListP buildList(int *arr, int n);
void Print();
int Length();
ListP FindKth(int K);
ListP Find(int x);
ListP changeANode( int n, int m);
ListP addANode(int n, int addedNum);
ListP Delete(int i);
ListP Clear();
};
list.cpp
#include "List.h"
ListP cList::pHead = NULL;
ListP cList::pTail = NULL;
ListP cList::buildList(int* arr, int n) {
pHead = NULL;
pTail = NULL;
for (int i = 0; i < n; i++) {
ListP tmp = new struct LNode(arr[i], NULL);
if (pHead==NULL) {
pHead = tmp;
pTail = tmp;
}
else {
pTail->Next = tmp;
pTail = tmp;
}
}
return pHead;
}
void cList::Print() {
ListP p = pHead;
while (p) {
cout << p->Data << " ";
p = p->Next;
}
if (pHead == NULL) {
cout << "isclear~"<<endl;
}
}
int cList::Length() {
ListP p = pHead;
int j = 0;
while (p) {
j++;
p = p->Next;
}
return j;
}
ListP cList::FindKth(int K) {
ListP p = pHead;
int i = 1;
while (p != NULL && i < K) {
p = p->Next;
i++;
}
if (i == K) {
return p;
}
else {
return NULL;
}
}
ListP cList::Find(int x) {
ListP p = pHead;
while (p != NULL && p->Data != x) {
p = p->Next;
}
if (p->Data == x) {
return p;
}
else {
return p;
}
}
ListP cList::addANode( int n, int addedNum) {
ListP p, s;
if (n == 1) {
s = (ListP)malloc(sizeof(struct LNode));
s->Data = addedNum;
s->Next = pHead;
pHead = s;
return pHead;
}
p = FindKth(n - 2);
if (p) {
cout << "参数n错误";
return NULL;
}
else {
s = (ListP)malloc(sizeof(struct LNode));
s->Data = addedNum;
s->Next = p->Next;
p->Next = s;
return s;
}
}
ListP cList::Delete(int i) {
ListP p, s;
if (i == 1) {
s = pHead;
if (pHead != NULL) {
pHead = pHead->Next;
}
else {
return NULL;
}
free(s);
return pHead;
}
p = FindKth(i - 1);
if (p == NULL) {
cout << "第" << i - 1 << "个结点不存在";
return NULL;
}
else if (p->Next == NULL) {
cout << "第" << i << "个结点不存在";
return NULL;
}
else {
s = p->Next;
p->Next = s->Next;
free(s);
return pHead;
}
}
ListP cList::changeANode(int n, int m) {
ListP p = FindKth(n);
if (p) {
p->Data = m;
return p;
}
else {
cout << "未找到对应元素";
return NULL;
}
}
ListP cList::Clear() {
while (Delete(1)) { }
return NULL;
}
#include"List.h"
int main() {
cList cl;
int arr[] = { 3,2,4,1,5,7,6,8 };
cl.buildList(arr, 8);
cl.Print();
cl.addANode(1, 99);
cout << endl;
cl.Print();
cl.Delete(1);
cout << endl;
cl.Print();
cl.Clear();
cl.Print();
return 0;
}
总结
f反正是能用吧,其实最好加上模板。
|