add linked list implementation and demo

This commit is contained in:
2EEEB 2021-02-24 10:35:47 +01:00
parent 07c34ee5aa
commit 6cd71941c0
Signed by: 2EEEB
GPG Key ID: 8F12BD6D9D435DB2
4 changed files with 137 additions and 0 deletions

74
wk3/list.cpp Normal file
View File

@ -0,0 +1,74 @@
#include "list.h"
List::List() {
List::InitNodes();
}
void List::InitNodes() {
head = NULL;
tail = NULL;
}
void List::disp() {
node *tmp;
tmp = head;
printf("** BEGIN\n");
while(tmp != NULL) {
printf("%5d\n", tmp->data);
tmp = tmp->next;
}
printf("** END\n");
}
void List::addNode(int d) {
node *tmp = new node;
tmp->data = d;
tmp->next = NULL;
if(head == NULL) {
head = tmp;
tail = tmp;
}
else {
tail->next = tmp;
tail = tail->next;
}
}
void List::addNodeToStart(int d) {
node *tmp = new node;
tmp -> data = d;
tmp -> next = head;
head = tmp;
}
void List::delNode() {
node *tmp;
tmp = head;
while(tmp) {
if(tmp -> next == tail) {
free(tmp -> next);
tail = tmp;
tail -> next = NULL;
}
else {
tmp = tmp -> next;
}
}
}
void List::delNodeFromStart() {
node *tmp;
tmp = head;
head = head -> next;
free(tmp);
}
void List::clear() {
node *tmp;
tmp = head;
while(tmp) {
tmp = tmp -> next;
delNodeFromStart();
}
}

27
wk3/list.h Normal file
View File

@ -0,0 +1,27 @@
//list.h
#include <iostream>
#include <stdlib.h>
#ifndef list
#define list
struct node {
int data;
node *next;
};
class List {
node *head, *tail;
public:
List();
void InitNodes();
void disp();
void addNode(int d);
void addNodeToStart(int d);
void delNode();
void delNodeFromStart();
void clear();
};
#endif

25
wk3/main.cpp Normal file
View File

@ -0,0 +1,25 @@
#include "list.h"
int main() {
List mylist;
mylist.disp();
mylist.addNode(1);
mylist.disp();
mylist.addNode(4);
mylist.disp();
mylist.addNode(8);
mylist.disp();
mylist.addNode(8);
mylist.disp();
mylist.addNodeToStart(8);
mylist.disp();
mylist.delNodeFromStart();
mylist.disp();
mylist.delNode();
mylist.disp();
mylist.addNode(9);
mylist.disp();
mylist.clear();
mylist.disp();
return 0;
}

11
wk3/makefile Normal file
View File

@ -0,0 +1,11 @@
CC = clang++
CFLAGS = -Os -Wall
TARGET = main
EXTS = list.cpp
DEPS = list.h
all: build
build:
$(CC) $(CFLAGS) $(EXTS) $(TARGET).cpp -o outf