diff --git a/wk3/list.cpp b/wk3/list.cpp new file mode 100644 index 0000000..5daee97 --- /dev/null +++ b/wk3/list.cpp @@ -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(); + } +} \ No newline at end of file diff --git a/wk3/list.h b/wk3/list.h new file mode 100644 index 0000000..1df9e98 --- /dev/null +++ b/wk3/list.h @@ -0,0 +1,27 @@ +//list.h +#include +#include + +#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 \ No newline at end of file diff --git a/wk3/main.cpp b/wk3/main.cpp new file mode 100644 index 0000000..336127c --- /dev/null +++ b/wk3/main.cpp @@ -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; +} diff --git a/wk3/makefile b/wk3/makefile new file mode 100644 index 0000000..2133a07 --- /dev/null +++ b/wk3/makefile @@ -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 \ No newline at end of file