Linked list practice using visual studio.

  1. Create a project in visual studio called LinkedListStudy
  2. Add a class named LinkedList to the program. (click project at the top and then click on add class.  Fill in the Class Name and then click  ok.  This should add LinkedList.h and LinkedList.cpp to your project.
  3. Add a method to this class called push_back(int x).  ( on the right hand side of the GUI bring up the Class View instead of the Solution Explorer.  Expand the LinkedListStudy so you can see the list of classes.  Now right click on the class LinkedList.  Select Add and then Add Function.  Fill in push_back as the name and then add an integer parameter.   Should look like the following before you click ok.  Continue from here modifying this class and then add the print() method.

 

Here are the three files we created in class today.

Here is the LinkedList.h file

#pragma once
#include <iostream>
using namespace std;
class LinkedList
{
struct Node {
int _val;
Node * _next;
Node(int v, Node* n) :_val(v), _next(n) {};
};
Node* _header;// will store the size in the headers _val variable.
Node* _last;
// You could also have placed the size variable here!! and not placed in in the header.

public:
LinkedList();
~LinkedList();
// This is the insert function. It adds a new item to the end of the linked list
void push_back(int n);
// Print out the Linked List on one line.
void print(int n);
};

Here is the LinkedList.cpp file

#include “stdafx.h”
#include “LinkedList.h”

// Default constructor that creates a header node only
LinkedList::LinkedList()
{
_last = _header = new Node(0, nullptr);
_header->_val = 0; // set the size to 0 to start
}

// Add the code for the instructor.
LinkedList::~LinkedList()
{
}
// This is the insert function. It adds a new item to the end of the linked list
void LinkedList::push_back(int n)
{
_last = _last->_next = new Node(n, nullptr);
_header->_val++; // increment the size within the header.
}
// Print out the Linked List on one line.
// Add the necessary code so that if n==0 print the entire list
// else print only n values . ie compare n with the size of the list
// change the while to a for .
void LinkedList::print(int n)
{
Node * tmp = _header->_next;
while (tmp != nullptr) {
cout << tmp->_val << ” “;
tmp = tmp->_next;
}
cout << endl;

}

Here is the LinkedListStudy.cpp file

// LinkedListStudy.cpp : Defines the entry point for the console application.
//

#include <iostream>
using namespace std;
#include “LinkedList.h”
int main()
{
LinkedList L;
L.push_back(3);
L.push_back(4);
L.push_back(5);
L.push_back(6);
L.print(0);
return 0;
}

 

Comments are closed.