add linked list implementation and demo
This commit is contained in:
parent
07c34ee5aa
commit
6cd71941c0
|
@ -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();
|
||||
}
|
||||
}
|
|
@ -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
|
|
@ -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;
|
||||
}
|
|
@ -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
|
Loading…
Reference in New Issue