123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119 |
- #include "Llist.h"
-
- void Llist::append(ElementType d){
- Node *n = new Node(d);
-
- // in case of empty list
- if (!head) {
- head = n;
- }
- // otherwise, non empty list...
- else {
- tail->next = n;
- }
- tail = n;
- length++;
- }
-
- void Llist::prepend(ElementType d) {
- Node *n = new Node(d, head);
-
- head = n;
- // in case of empty list the tail = head = n
- if (length == 0) tail = n;
-
- length++;
- }
-
- void Llist::display(ostream &out) const {
- Node *p = head;
- while(p) {
- out << p->data << " ";
- p = p->next;
- }
- }
-
- void Llist::insertAfter(Node *p, ElementType d) {
- Node *n;
- if (p == NULL) {
- n = new Node(d, head);
- head = n;
- if (!tail) tail = n;
- }
- else {
- n = new Node (d, p->next);
- p->next = n;
- if (tail == p) tail = n;
- }
- length++;
- }
-
- Node* Llist::search(ElementType d) const {
- Node *p = head;
- while(p) {
- if (p->data == d) return p;
- p = p->next;
- }
- return NULL;
- }
-
- ostream& operator<< (ostream &out, const Llist& L) {
- L.display(out);
- return out;
- }
-
- void Llist::printRev() const {
- printRev(head);
- }
- void Llist::printRev(Node *p) const {
- if (p != NULL) {
- printRev(p->next);
- cout << p->data << endl;
- }
- }
-
- void Llist::removeAfter(Node *cur) {
- Node *suc;
- if (cur == NULL and head != NULL) {
- suc = head->next;
- delete head;
- head = suc;
-
- if (suc == NULL) tail = NULL;
- }
- else if (cur->next != NULL) {
- suc = cur->next->next;
- delete cur->next;
- cur->next = suc;
- if (suc == NULL) tail = cur;
- }
- length--;
- }
-
- Llist& Llist::operator=(const Llist &L) {
- if (this != &L) {
- while(head != NULL) removeAfter(NULL);
- Node *cur = L.head;
- while (cur != NULL) {
- append(cur->data);
- cur = cur->next;
- }
- }
- return *this;
- }
-
- Llist::Llist(const Llist &L) {
- head = tail = NULL;
- length = 0;
- if (this != &L) {
- Node *cur = L.head;
- while (cur != NULL) {
- append(cur->data);
- cur = cur->next;
- }
- }
- }
-
- Llist::~Llist() {
- while(head != NULL) removeAfter(NULL);
- }
|