Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jonathan-nwosu/5e3280c1f8e089e9425625ba7fedcd89 to your computer and use it in GitHub Desktop.
Save jonathan-nwosu/5e3280c1f8e089e9425625ba7fedcd89 to your computer and use it in GitHub Desktop.
//
// main.cpp
// Linked_list(recursion)
//
// Created by Jonathan Nwosu on 03/04/2017.
// Copyright © 2017 Jonathan Nwosu. All rights reserved.
//
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
struct Node {
int data;
struct Node* next;
};
//name of particular argument is p which will be a local variable
void Print(struct Node* p){
if(p == NULL) return; //exit conditions
//swapping the 2 lines below reverses the linked list
printf("%d", p->data); //print value at a particular node
Print(p->next); //adress of the next node // ie recursive xall
}
//reverse printing
void ReversePrint(struct Node* p){
if(p == NULL){
return;
}
ReversePrint(p->next);
printf("%d", p->data);
}
//insert function...
struct Node* Insert(Node* head, int data){
Node *temp = (struct Node*)malloc(sizeof(struct Node));
temp -> data = data;
temp -> next = NULL;
if(head == NULL) head = temp;
else {
Node* temp1 = head;
while(temp1->next != NULL) temp1 = temp1->next;
temp1->next = temp;
}
return head;
}
int main() {
struct Node* head = NULL; //local variable variable points to head node or first head on list..
head = Insert(head,2); // 2 parameters, adress of head node (intially set to 0), value inserted
head = Insert(head,4);
head = Insert(head,6);
head = Insert(head,5);
//now we make a call to the print function and pass on the address of the head node
Print(head);
cout << endl;
ReversePrint(head);
cout << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment