Skip to content

Instantly share code, notes, and snippets.

@jonathan-nwosu
Last active May 19, 2017 18:47
Show Gist options
  • Save jonathan-nwosu/a9917e40044344d1a7e0b377e72e2d73 to your computer and use it in GitHub Desktop.
Save jonathan-nwosu/a9917e40044344d1a7e0b377e72e2d73 to your computer and use it in GitHub Desktop.
//
// main.cpp
// doubly_linked_list
//
// Created by Jonathan Nwosu on 04/04/2017.
// Copyright © 2017 Jonathan Nwosu. All rights reserved.
//
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
struct node{
int data;
node* next;
node* prev;
};
//now we define our functions outsie the main function...
void PrintForward(node* head); //example of prototyping
void PrintReverse(node* tail); //prototyping again...
int main() {
//define what a doubly linked list will look like...
//want node to contain an integer data value...
//want also a node pointer to move node to the next node
//want a node pointer to point to move to the previous node in list
node* head; //defining the head node
node* tail; //defining the tail node at the very end of the linkedlist
node* n; //short for new
n = new node;
n->data = 1; // the data that the node holds
n->prev = NULL; //very begining node doesn't point to anything...
head = n;
tail = n; //holds value of 1
n = new node;
n->data = 2;
n->prev = tail; //in this case tail pointer points to 1
tail -> next = n; // the other tail pointer points to the next node
tail = n;
n = new node;
n->data = 3;
n->prev = tail;
tail->next = n;
tail = n;
n = new node;
n->data = 4;
n->prev = tail; //pointer from previous node points to
tail->next = n;
tail = n;
tail -> next = NULL; //very last node doesn't point to anything...
PrintForward(head);
PrintReverse(tail); //reversing a linkedlist
return 0;
}
void PrintForward(node* head){ // iniitializing a function pointer, pointer name is called node
node* temp = head;
while (temp != NULL){
cout << temp ->data << "" ;
temp = temp->next;
}
cout << endl;
}
void PrintReverse(node* tail){
node* temp = tail;
while (temp != NULL){
cout << temp ->data << "" ;
temp = temp->prev;
}
cout << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment