SlideShare ist ein Scribd-Unternehmen logo
1 von 10
#include "stdafx.h"
struct Node
{
int data;
Node* next;
Node() = default;
Node(int _data, Node* _next) : data(_data), next(_next){};
};
// run sample code
void RunLL()
{
//Node *head = new Node;
//Node* lt = nullptr;
//Node* gt = nullptr;
//InitNode(head, 122);
//DisplayList(head);
//AddEndNode(head, 60);
//DisplayList(head);
//AddEndNode(head, 182);
//DisplayList(head);
//AddEndNode(head, 2);
//DisplayList(head);
//AddEndNode(head, 202);
//DisplayList(head);
//InsertFront(&head, 15);
//DisplayList(head);
//SortListAscending(head, head);
//DisplayList(head);
//AddSortedNode(head, 86);
//DisplayList(head);
//Node* midNode = FindMiddleNode(head);
//cout << midNode->data << endl << endl;
//bool circular = IsCircular(head);
//string disp = circular ? "true" : "false";
//cout << disp << endl << endl;
//Split(head, 86, &lt, &gt);
//DisplayList(lt);
//DisplayList(gt);
//int numDel = 15;
//Node *ptrDelete = FindANode(head, numDel);
//if (DeleteNode(head, ptrDelete->data))
// cout << numDel << " deleted!n";
//DisplayList(head);
//cout << "The list is reversedn";
//ReverseList(&head);
//DisplayList(head);
//numDel = 60;
//ptrDelete = FindANode(head, numDel);
//if (DeleteNode(head, ptrDelete->data))
//{
// cout << numDel << " deleted!n";
// DisplayList(head);
//}
//if (!circular)
// MakeCircular(head);
//circular = IsCircular(head);
//disp = circular ? "true" : "false";
//cout << disp << endl << endl;
}
// only for the 1st Node
void InitNode(Node* head, int n)
{
head->data = n;
head->next = NULL;
}
Node* TestList()
{
Node* head = new Node;
InitNode(head, 0);
head->next = new Node(3, nullptr);
head->next->next = new Node(7, nullptr);
return head;
}
void DelList(Node* head)
{
if (head->next)
DelList(head->next);
delete head;
}
// find a node with value 'd' (start with head to search entire list)
Node* FindANode(Node* currNode, int d)
{
// end of list, node not found
if (!currNode) return nullptr;
// node found
if (currNode->data == d)
return currNode;
// check next node
FindANode(currNode->next, d);
}
// add new node to end of list
void AddEndNode(Node* currNode, int d)
{
// move on to next node
if (currNode->next)
AddEndNode(currNode->next, d);
else // found end of list, add new node
{
currNode->next = new Node(d, nullptr);
return;
}
}
// add new node to front of list
void InsertFront(Node** head, int n)
{
Node *newNode = new Node;
newNode->data = n;
newNode->next = *head;
*head = newNode;
}
// delete node
bool DeleteNode(Node* currNode, int val)
{
if (!currNode || !currNode->next) return false;
// node found, 'delete' it
if (currNode->next->data == val)
{
Node* tempNode = currNode->next;
currNode->next = currNode->next->next;
delete tempNode;
return true;
}
// check next node
else if (DeleteNode(currNode->next, val))
return true;
// node not found
return false;
}
// add new node (sorted list)
void AddSortedNode(Node* currNode, int d)
{
// list is empty or 'd' becomes head
if (!currNode || currNode->data > d)
{
InsertFront(&currNode, d);
return;
}
// at end of list
if (!currNode->next)
{
AddEndNode(currNode, d);
return;
}
// insert newNode here
if ((currNode->data <= d && currNode->next->data > d)
|| (currNode->data > d && currNode->next->data < d))
{
Node* newNode = new Node;
newNode->data = d;
newNode->next = currNode->next;
currNode->next = newNode;
return;
}
// check next node
AddSortedNode(currNode->next, d);
}
// split a list into two lists (less than, greater than)
void Split(Node* head, int pivot, Node** lt, Node** gt)
{
if (!head) return;
if (head->data < pivot)
{
if (*lt)
AddEndNode(*lt, head->data);
else
{
*lt = new Node;
InitNode(*lt, head->data);
}
}
else if (head->data > pivot)
{
if (*gt)
AddEndNode(*gt, head->data);
else
{
*gt = new Node;
InitNode(*gt, head->data);
}
}
Split(head->next, pivot, lt, gt);
}
// reverse a list
void ReverseList(Node** currNode)
{
// list is empty || has only one node || at end of list
if (!(*currNode) || !(*currNode)->next) return;
// move newCurrNode to the end of the list
Node* newCurrNode = (*currNode)->next;
ReverseList(&newCurrNode);
// reverse the 'next' pointers (next->next is validated by earlier 'if check')
(*currNode)->next->next = (*currNode);
// set 'next' ptr to nullptr
(*currNode)->next = nullptr;
// fix the currNode / 'head' pointer and return it
*currNode = newCurrNode;
}
// sort the list
void SortListAscending(Node* firstNode, Node* currNode)
{
// recursive
#if 1
// swap data
if (currNode->data < firstNode->data)
{
int tmpData = firstNode->data;
firstNode->data = currNode->data;
currNode->data = tmpData;
}
// second / inner 'loop'
if (currNode->next)
SortListAscending(firstNode, currNode->next);
// first / outer 'loop'
else if (firstNode->next)
SortListAscending(firstNode->next, firstNode->next);
#endif
// while loop
#if 0
Node* iter = firstNode;
while (iter)
{
Node* iter2 = firstNode;
while (iter2->next)
{
if (iter->data < iter2->data)
{
int tmpData = iter->data;
iter->data = iter2->data;
iter2->data = tmpData;
}
iter2 = iter2->next;
}
iter = iter->next;
}
#endif
}
// is a list circular (count is used to avoid returning on first cycle)
bool IsCircular(Node* head)
{
// list is empty || hare reached end of list (not circular)
if (!head) return false;
int count = 1;
Node* tortoise = head;
Node* hare = head;
while (hare->next)
{
// move the 'tortoise' ptr once every other cycle
if (count++ % 2 == 0) tortoise = tortoise->next;
hare = hare->next;
// tortoise caught up to the hare (circular list)
if (tortoise == hare && count > 1) return true;
}
return false;
}
// make the list circular
void MakeCircular(Node* head)
{
if (!head) return;
Node* currNode = head;
while (currNode->next)
currNode = currNode->next;
currNode->next = head;
}
// find middle node in a list
Node* FindMiddleNode(Node* head)
{
Node* currNode = head;
Node* midNode = head;
int count = 1;
while (currNode->next)
{
if (count++ % 2 == 0)
midNode = midNode->next;
currNode = currNode->next;
}
return midNode;
}
// disply list from currNode (pass 'head' to display entire list)
void DisplayList(Node *currNode)
{
// display currNode
//cout << currNode->data << " ";
//// if available, move to next node
//if (currNode->next)
// DisplayList(currNode->next);
//// if not, insert two lines for end of list
//else
// cout << "nn";
}
BOOST_AUTO_TEST_SUITE(LinkedLists)
BOOST_AUTO_TEST_CASE(FindNode)
{
Node* head = TestList();
Node* tgt = FindANode(head, 3);
// should fail
//BOOST_CHECK_EQUAL(tgt->data, 11);
// should pass
BOOST_CHECK_EQUAL(tgt->data, 3);
DelList(head);
}
BOOST_AUTO_TEST_CASE(AddToEnd)
{
Node* head = TestList();
AddEndNode(head, 11);
Node* tgt = FindANode(head, 11);
// should fail
//BOOST_CHECK(tgt->next);
// should pass
BOOST_CHECK(!tgt->next);
DelList(head);
}
BOOST_AUTO_TEST_CASE(AddFront)
{
Node* head = TestList();
InsertFront(&head, 11);
Node* tgt = FindANode(head, 11);
// should fail
//BOOST_CHECK_EQUAL(tgt->data, 20);
// should pass
BOOST_CHECK_EQUAL(tgt, head);
DelList(head);
}
BOOST_AUTO_TEST_CASE(DelNode)
{
Node* head = TestList();
DeleteNode(head, 11);
// should fail
//BOOST_CHECK(FindANode(head, 3) == nullptr);
// should pass
BOOST_CHECK(FindANode(head, 11) == nullptr);
DelList(head);
}
// sorted item added to head of list
BOOST_AUTO_TEST_CASE(AddSortedHead)
{
Node* head = TestList();
AddSortedNode(head, 0);
// should fail
//BOOST_CHECK_EQUAL(head->data, 3);
// should pass
BOOST_CHECK(head->data == 0);
DelList(head);
}
// sorted item added to mid of list
BOOST_AUTO_TEST_CASE(AddSortedMid)
{
Node* head = TestList();
AddSortedNode(head, 6);
Node* prev = head;
Node* newNode = FindANode(head, 6);
// find newNode->previous
while (prev->next->data < newNode->data)
prev = prev->next;
// check if newNode is mid list
BOOST_CHECK(prev->data <= newNode->data);
BOOST_CHECK(newNode->next);
DelList(head);
}
// sorted item added to end of list
BOOST_AUTO_TEST_CASE(AddSortedEnd)
{
Node* head = TestList();
AddSortedNode(head, 60);
Node*prev = head;
Node* newNode = FindANode(head, 60);
// find newNode-previous
while (prev->next->data < newNode->data)
prev = prev->next;
// check newNode is end of list (correctly)
BOOST_CHECK(prev->data <= newNode->data);
BOOST_CHECK(!newNode->next);
DelList(head);
}
BOOST_AUTO_TEST_CASE(SplitList)
{
Node* head = TestList();
Node* ltList = nullptr;
Node* gtList = nullptr;
// create 2 new lists from first list
Split(head, 3, &ltList, &gtList);
Node* ltEnd = ltList;
while (ltEnd->next)
ltEnd = ltEnd->next;
BOOST_CHECK(ltEnd->data < gtList->data);
DelList(head);
delete ltList;
delete gtList;
}
BOOST_AUTO_TEST_CASE(RevList)
{
Node* head = TestList();
ReverseList(&head);
// should fail
//BOOST_CHECK_EQUAL(head->data, 0);
// should pass
BOOST_CHECK_EQUAL(head->data, 7);
BOOST_CHECK_EQUAL(head->next->data, 3);
BOOST_CHECK_EQUAL(head->next->next->data, 0);
DelList(head);
}
BOOST_AUTO_TEST_CASE(SortAsc)
{
Node* head = TestList();
int tmp = head->data;
// change list to 3, 7, 0
head->data = head->next->data;
head->next->data = tmp;
tmp = head->next->data;
head->next->data = head->next->next->data;
head->next->next->data = tmp;
// change back to 0, 3, 7
SortListAscending(head, head);
// should fail
//BOOST_CHECK_EQUAL(head->data, 3);
// should pass
BOOST_CHECK_EQUAL(head->data, 0);
BOOST_CHECK_EQUAL(head->next->data, 3);
BOOST_CHECK_EQUAL(head->next->next->data, 7);
DelList(head);
}
BOOST_AUTO_TEST_CASE(CheckCircular)
{
}
BOOST_AUTO_TEST_CASE(BeCircular)
{
}
BOOST_AUTO_TEST_CASE(FindMiddle)
{
}
BOOST_AUTO_TEST_SUITE_END()

Weitere ähnliche Inhalte

Was ist angesagt?

SWP - A Generic Language Parser
SWP - A Generic Language ParserSWP - A Generic Language Parser
SWP - A Generic Language Parserkamaelian
 
The Ring programming language version 1.9 book - Part 91 of 210
The Ring programming language version 1.9 book - Part 91 of 210The Ring programming language version 1.9 book - Part 91 of 210
The Ring programming language version 1.9 book - Part 91 of 210Mahmoud Samir Fayed
 
My All Codes of SAS
My All Codes of SASMy All Codes of SAS
My All Codes of SASrizrazariz
 
vfsStream - effective filesystem mocking
vfsStream - effective filesystem mocking vfsStream - effective filesystem mocking
vfsStream - effective filesystem mocking Sebastian Marek
 
vfsStream - a better approach for file system dependent tests
vfsStream - a better approach for file system dependent testsvfsStream - a better approach for file system dependent tests
vfsStream - a better approach for file system dependent testsFrank Kleine
 
SAS codes and tricks Comprehensive all codes
SAS codes and tricks Comprehensive all codesSAS codes and tricks Comprehensive all codes
SAS codes and tricks Comprehensive all codesrizrazariz
 
SAS codes and tricks Comprehensive all codess
SAS codes and tricks Comprehensive all codessSAS codes and tricks Comprehensive all codess
SAS codes and tricks Comprehensive all codessrizrazariz
 
寫程式?那些老師沒教的事
寫程式?那些老師沒教的事寫程式?那些老師沒教的事
寫程式?那些老師沒教的事均民 戴
 
Melhorando sua API com DSLs
Melhorando sua API com DSLsMelhorando sua API com DSLs
Melhorando sua API com DSLsAugusto Pascutti
 
寫程式?那些老師沒教的事 (Git 部分節錄)
寫程式?那些老師沒教的事 (Git 部分節錄)寫程式?那些老師沒教的事 (Git 部分節錄)
寫程式?那些老師沒教的事 (Git 部分節錄)均民 戴
 
First Steps. (db4o - Object Oriented Database)
First Steps. (db4o - Object Oriented Database)First Steps. (db4o - Object Oriented Database)
First Steps. (db4o - Object Oriented Database)Wildan Maulana
 

Was ist angesagt? (18)

Javascript
JavascriptJavascript
Javascript
 
C99
C99C99
C99
 
Mod04 debuggers
Mod04 debuggersMod04 debuggers
Mod04 debuggers
 
SWP - A Generic Language Parser
SWP - A Generic Language ParserSWP - A Generic Language Parser
SWP - A Generic Language Parser
 
C99.php
C99.phpC99.php
C99.php
 
The Ring programming language version 1.9 book - Part 91 of 210
The Ring programming language version 1.9 book - Part 91 of 210The Ring programming language version 1.9 book - Part 91 of 210
The Ring programming language version 1.9 book - Part 91 of 210
 
My All Codes of SAS
My All Codes of SASMy All Codes of SAS
My All Codes of SAS
 
Cod
CodCod
Cod
 
vfsStream - effective filesystem mocking
vfsStream - effective filesystem mocking vfsStream - effective filesystem mocking
vfsStream - effective filesystem mocking
 
vfsStream - a better approach for file system dependent tests
vfsStream - a better approach for file system dependent testsvfsStream - a better approach for file system dependent tests
vfsStream - a better approach for file system dependent tests
 
SAS codes and tricks Comprehensive all codes
SAS codes and tricks Comprehensive all codesSAS codes and tricks Comprehensive all codes
SAS codes and tricks Comprehensive all codes
 
SAS codes and tricks Comprehensive all codess
SAS codes and tricks Comprehensive all codessSAS codes and tricks Comprehensive all codess
SAS codes and tricks Comprehensive all codess
 
zinno
zinnozinno
zinno
 
寫程式?那些老師沒教的事
寫程式?那些老師沒教的事寫程式?那些老師沒教的事
寫程式?那些老師沒教的事
 
Melhorando sua API com DSLs
Melhorando sua API com DSLsMelhorando sua API com DSLs
Melhorando sua API com DSLs
 
寫程式?那些老師沒教的事 (Git 部分節錄)
寫程式?那些老師沒教的事 (Git 部分節錄)寫程式?那些老師沒教的事 (Git 部分節錄)
寫程式?那些老師沒教的事 (Git 部分節錄)
 
Five
FiveFive
Five
 
First Steps. (db4o - Object Oriented Database)
First Steps. (db4o - Object Oriented Database)First Steps. (db4o - Object Oriented Database)
First Steps. (db4o - Object Oriented Database)
 

Andere mochten auch (14)

Kmc presentation
Kmc presentationKmc presentation
Kmc presentation
 
How to Simplify Enterprise Collaboration Using Enterprise Portals
How to Simplify Enterprise Collaboration Using Enterprise Portals How to Simplify Enterprise Collaboration Using Enterprise Portals
How to Simplify Enterprise Collaboration Using Enterprise Portals
 
SWISSWAY 1500
SWISSWAY 1500SWISSWAY 1500
SWISSWAY 1500
 
SWISS BULLION TABLES
SWISS BULLION TABLESSWISS BULLION TABLES
SWISS BULLION TABLES
 
The racer
The racerThe racer
The racer
 
Taller de robótica2 copy
Taller de robótica2   copyTaller de robótica2   copy
Taller de robótica2 copy
 
US APPAREL BOARDSHORT CATALOG 2017
US APPAREL BOARDSHORT CATALOG 2017US APPAREL BOARDSHORT CATALOG 2017
US APPAREL BOARDSHORT CATALOG 2017
 
SWISS BULLION
SWISS BULLION SWISS BULLION
SWISS BULLION
 
P.C.MISHRA Resume
P.C.MISHRA ResumeP.C.MISHRA Resume
P.C.MISHRA Resume
 
Atul Joshi - Oct 2016
Atul Joshi - Oct 2016Atul Joshi - Oct 2016
Atul Joshi - Oct 2016
 
All Strategies
All StrategiesAll Strategies
All Strategies
 
Saleem Lawati CV
Saleem Lawati CVSaleem Lawati CV
Saleem Lawati CV
 
How Cloud Computing is changing the Automotive Industry - KNOWARTH
How Cloud Computing is changing the Automotive Industry - KNOWARTHHow Cloud Computing is changing the Automotive Industry - KNOWARTH
How Cloud Computing is changing the Automotive Industry - KNOWARTH
 
Gyasi et al, 2015b
Gyasi et al, 2015bGyasi et al, 2015b
Gyasi et al, 2015b
 

Ähnlich wie Linked lists

mainpublic class AssignmentThree {    public static void ma.pdf
mainpublic class AssignmentThree {    public static void ma.pdfmainpublic class AssignmentThree {    public static void ma.pdf
mainpublic class AssignmentThree {    public static void ma.pdffathimafancyjeweller
 
Binary Tree in C++ coding in the data structure
Binary Tree in C++ coding in the data structureBinary Tree in C++ coding in the data structure
Binary Tree in C++ coding in the data structureZarghamullahShah
 
#includeiostream #includecstdio #includecstdlib using na.pdf
#includeiostream #includecstdio #includecstdlib using na.pdf#includeiostream #includecstdio #includecstdlib using na.pdf
#includeiostream #includecstdio #includecstdlib using na.pdfharihelectronicspune
 
tested on eclipseDoublyLinkedList class.pdf
tested on eclipseDoublyLinkedList class.pdftested on eclipseDoublyLinkedList class.pdf
tested on eclipseDoublyLinkedList class.pdfshanki7
 
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjhlinked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjhvasavim9
 
includestdio.h #includestdlib.h int enqueue(struct node ,.pdf
includestdio.h #includestdlib.h int enqueue(struct node ,.pdfincludestdio.h #includestdlib.h int enqueue(struct node ,.pdf
includestdio.h #includestdlib.h int enqueue(struct node ,.pdfgalagirishp
 
Program to insert in a sorted list #includestdio.h#include.pdf
 Program to insert in a sorted list #includestdio.h#include.pdf Program to insert in a sorted list #includestdio.h#include.pdf
Program to insert in a sorted list #includestdio.h#include.pdfsudhirchourasia86
 
Note             Given Code modified as required and required met.pdf
Note             Given Code modified as required and required met.pdfNote             Given Code modified as required and required met.pdf
Note             Given Code modified as required and required met.pdfAnkitchhabra28
 
#ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf
 #ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf #ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf
#ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdfangelsfashion1
 
in this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfin this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfmichardsonkhaicarr37
 
#includeiostream#includecstdio#includecstdlibusing names.pdf
#includeiostream#includecstdio#includecstdlibusing names.pdf#includeiostream#includecstdio#includecstdlibusing names.pdf
#includeiostream#includecstdio#includecstdlibusing names.pdfKUNALHARCHANDANI1
 
Lab Week 2 Game Programming.docx
Lab Week 2 Game Programming.docxLab Week 2 Game Programming.docx
Lab Week 2 Game Programming.docxteyaj1
 
Using the provided table interface table.h and the sample linked lis.pdf
Using the provided table interface table.h and the sample linked lis.pdfUsing the provided table interface table.h and the sample linked lis.pdf
Using the provided table interface table.h and the sample linked lis.pdfconnellalykshamesb60
 
Please finish the int LLInsert function.typedef struct STUDENT {.pdf
Please finish the int LLInsert function.typedef struct STUDENT {.pdfPlease finish the int LLInsert function.typedef struct STUDENT {.pdf
Please finish the int LLInsert function.typedef struct STUDENT {.pdffortmdu
 
Data structure circular list
Data structure circular listData structure circular list
Data structure circular listiCreateWorld
 
solution in c++program Program to implement a queue using two .pdf
solution in c++program Program to implement a queue using two .pdfsolution in c++program Program to implement a queue using two .pdf
solution in c++program Program to implement a queue using two .pdfbrijmote
 
In C++Write a recursive function to determine whether or not a Lin.pdf
In C++Write a recursive function to determine whether or not a Lin.pdfIn C++Write a recursive function to determine whether or not a Lin.pdf
In C++Write a recursive function to determine whether or not a Lin.pdfflashfashioncasualwe
 
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYDATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYMalikireddy Bramhananda Reddy
 

Ähnlich wie Linked lists (20)

mainpublic class AssignmentThree {    public static void ma.pdf
mainpublic class AssignmentThree {    public static void ma.pdfmainpublic class AssignmentThree {    public static void ma.pdf
mainpublic class AssignmentThree {    public static void ma.pdf
 
Binary Tree in C++ coding in the data structure
Binary Tree in C++ coding in the data structureBinary Tree in C++ coding in the data structure
Binary Tree in C++ coding in the data structure
 
#includeiostream #includecstdio #includecstdlib using na.pdf
#includeiostream #includecstdio #includecstdlib using na.pdf#includeiostream #includecstdio #includecstdlib using na.pdf
#includeiostream #includecstdio #includecstdlib using na.pdf
 
tested on eclipseDoublyLinkedList class.pdf
tested on eclipseDoublyLinkedList class.pdftested on eclipseDoublyLinkedList class.pdf
tested on eclipseDoublyLinkedList class.pdf
 
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjhlinked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
 
includestdio.h #includestdlib.h int enqueue(struct node ,.pdf
includestdio.h #includestdlib.h int enqueue(struct node ,.pdfincludestdio.h #includestdlib.h int enqueue(struct node ,.pdf
includestdio.h #includestdlib.h int enqueue(struct node ,.pdf
 
Program to insert in a sorted list #includestdio.h#include.pdf
 Program to insert in a sorted list #includestdio.h#include.pdf Program to insert in a sorted list #includestdio.h#include.pdf
Program to insert in a sorted list #includestdio.h#include.pdf
 
Note             Given Code modified as required and required met.pdf
Note             Given Code modified as required and required met.pdfNote             Given Code modified as required and required met.pdf
Note             Given Code modified as required and required met.pdf
 
#ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf
 #ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf #ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf
#ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf
 
in this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfin this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdf
 
DS Code (CWH).docx
DS Code (CWH).docxDS Code (CWH).docx
DS Code (CWH).docx
 
#includeiostream#includecstdio#includecstdlibusing names.pdf
#includeiostream#includecstdio#includecstdlibusing names.pdf#includeiostream#includecstdio#includecstdlibusing names.pdf
#includeiostream#includecstdio#includecstdlibusing names.pdf
 
Lab Week 2 Game Programming.docx
Lab Week 2 Game Programming.docxLab Week 2 Game Programming.docx
Lab Week 2 Game Programming.docx
 
Using the provided table interface table.h and the sample linked lis.pdf
Using the provided table interface table.h and the sample linked lis.pdfUsing the provided table interface table.h and the sample linked lis.pdf
Using the provided table interface table.h and the sample linked lis.pdf
 
Please finish the int LLInsert function.typedef struct STUDENT {.pdf
Please finish the int LLInsert function.typedef struct STUDENT {.pdfPlease finish the int LLInsert function.typedef struct STUDENT {.pdf
Please finish the int LLInsert function.typedef struct STUDENT {.pdf
 
week-14x
week-14xweek-14x
week-14x
 
Data structure circular list
Data structure circular listData structure circular list
Data structure circular list
 
solution in c++program Program to implement a queue using two .pdf
solution in c++program Program to implement a queue using two .pdfsolution in c++program Program to implement a queue using two .pdf
solution in c++program Program to implement a queue using two .pdf
 
In C++Write a recursive function to determine whether or not a Lin.pdf
In C++Write a recursive function to determine whether or not a Lin.pdfIn C++Write a recursive function to determine whether or not a Lin.pdf
In C++Write a recursive function to determine whether or not a Lin.pdf
 
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYDATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
 

Mehr von George Scott IV

Mehr von George Scott IV (7)

Square selection function
Square selection functionSquare selection function
Square selection function
 
Save game function
Save game functionSave game function
Save game function
 
Delete save from folder function
Delete save from folder functionDelete save from folder function
Delete save from folder function
 
Trees
TreesTrees
Trees
 
Strings
StringsStrings
Strings
 
Misc
MiscMisc
Misc
 
Arrays
ArraysArrays
Arrays
 

Kürzlich hochgeladen

Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 

Kürzlich hochgeladen (20)

Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 

Linked lists

  • 1. #include "stdafx.h" struct Node { int data; Node* next; Node() = default; Node(int _data, Node* _next) : data(_data), next(_next){}; }; // run sample code void RunLL() { //Node *head = new Node; //Node* lt = nullptr; //Node* gt = nullptr; //InitNode(head, 122); //DisplayList(head); //AddEndNode(head, 60); //DisplayList(head); //AddEndNode(head, 182); //DisplayList(head); //AddEndNode(head, 2); //DisplayList(head); //AddEndNode(head, 202); //DisplayList(head); //InsertFront(&head, 15); //DisplayList(head); //SortListAscending(head, head); //DisplayList(head); //AddSortedNode(head, 86); //DisplayList(head); //Node* midNode = FindMiddleNode(head); //cout << midNode->data << endl << endl; //bool circular = IsCircular(head); //string disp = circular ? "true" : "false"; //cout << disp << endl << endl; //Split(head, 86, &lt, &gt); //DisplayList(lt); //DisplayList(gt); //int numDel = 15; //Node *ptrDelete = FindANode(head, numDel); //if (DeleteNode(head, ptrDelete->data)) // cout << numDel << " deleted!n"; //DisplayList(head);
  • 2. //cout << "The list is reversedn"; //ReverseList(&head); //DisplayList(head); //numDel = 60; //ptrDelete = FindANode(head, numDel); //if (DeleteNode(head, ptrDelete->data)) //{ // cout << numDel << " deleted!n"; // DisplayList(head); //} //if (!circular) // MakeCircular(head); //circular = IsCircular(head); //disp = circular ? "true" : "false"; //cout << disp << endl << endl; } // only for the 1st Node void InitNode(Node* head, int n) { head->data = n; head->next = NULL; } Node* TestList() { Node* head = new Node; InitNode(head, 0); head->next = new Node(3, nullptr); head->next->next = new Node(7, nullptr); return head; } void DelList(Node* head) { if (head->next) DelList(head->next); delete head; } // find a node with value 'd' (start with head to search entire list) Node* FindANode(Node* currNode, int d) { // end of list, node not found if (!currNode) return nullptr; // node found if (currNode->data == d) return currNode; // check next node FindANode(currNode->next, d); }
  • 3. // add new node to end of list void AddEndNode(Node* currNode, int d) { // move on to next node if (currNode->next) AddEndNode(currNode->next, d); else // found end of list, add new node { currNode->next = new Node(d, nullptr); return; } } // add new node to front of list void InsertFront(Node** head, int n) { Node *newNode = new Node; newNode->data = n; newNode->next = *head; *head = newNode; } // delete node bool DeleteNode(Node* currNode, int val) { if (!currNode || !currNode->next) return false; // node found, 'delete' it if (currNode->next->data == val) { Node* tempNode = currNode->next; currNode->next = currNode->next->next; delete tempNode; return true; } // check next node else if (DeleteNode(currNode->next, val)) return true; // node not found return false; } // add new node (sorted list) void AddSortedNode(Node* currNode, int d) { // list is empty or 'd' becomes head if (!currNode || currNode->data > d) { InsertFront(&currNode, d); return; } // at end of list if (!currNode->next) { AddEndNode(currNode, d);
  • 4. return; } // insert newNode here if ((currNode->data <= d && currNode->next->data > d) || (currNode->data > d && currNode->next->data < d)) { Node* newNode = new Node; newNode->data = d; newNode->next = currNode->next; currNode->next = newNode; return; } // check next node AddSortedNode(currNode->next, d); } // split a list into two lists (less than, greater than) void Split(Node* head, int pivot, Node** lt, Node** gt) { if (!head) return; if (head->data < pivot) { if (*lt) AddEndNode(*lt, head->data); else { *lt = new Node; InitNode(*lt, head->data); } } else if (head->data > pivot) { if (*gt) AddEndNode(*gt, head->data); else { *gt = new Node; InitNode(*gt, head->data); } } Split(head->next, pivot, lt, gt); } // reverse a list void ReverseList(Node** currNode) { // list is empty || has only one node || at end of list if (!(*currNode) || !(*currNode)->next) return; // move newCurrNode to the end of the list Node* newCurrNode = (*currNode)->next; ReverseList(&newCurrNode); // reverse the 'next' pointers (next->next is validated by earlier 'if check') (*currNode)->next->next = (*currNode);
  • 5. // set 'next' ptr to nullptr (*currNode)->next = nullptr; // fix the currNode / 'head' pointer and return it *currNode = newCurrNode; } // sort the list void SortListAscending(Node* firstNode, Node* currNode) { // recursive #if 1 // swap data if (currNode->data < firstNode->data) { int tmpData = firstNode->data; firstNode->data = currNode->data; currNode->data = tmpData; } // second / inner 'loop' if (currNode->next) SortListAscending(firstNode, currNode->next); // first / outer 'loop' else if (firstNode->next) SortListAscending(firstNode->next, firstNode->next); #endif // while loop #if 0 Node* iter = firstNode; while (iter) { Node* iter2 = firstNode; while (iter2->next) { if (iter->data < iter2->data) { int tmpData = iter->data; iter->data = iter2->data; iter2->data = tmpData; } iter2 = iter2->next; } iter = iter->next; } #endif } // is a list circular (count is used to avoid returning on first cycle) bool IsCircular(Node* head) { // list is empty || hare reached end of list (not circular) if (!head) return false; int count = 1; Node* tortoise = head;
  • 6. Node* hare = head; while (hare->next) { // move the 'tortoise' ptr once every other cycle if (count++ % 2 == 0) tortoise = tortoise->next; hare = hare->next; // tortoise caught up to the hare (circular list) if (tortoise == hare && count > 1) return true; } return false; } // make the list circular void MakeCircular(Node* head) { if (!head) return; Node* currNode = head; while (currNode->next) currNode = currNode->next; currNode->next = head; } // find middle node in a list Node* FindMiddleNode(Node* head) { Node* currNode = head; Node* midNode = head; int count = 1; while (currNode->next) { if (count++ % 2 == 0) midNode = midNode->next; currNode = currNode->next; } return midNode; } // disply list from currNode (pass 'head' to display entire list) void DisplayList(Node *currNode) { // display currNode //cout << currNode->data << " "; //// if available, move to next node //if (currNode->next) // DisplayList(currNode->next); //// if not, insert two lines for end of list //else // cout << "nn"; }
  • 7. BOOST_AUTO_TEST_SUITE(LinkedLists) BOOST_AUTO_TEST_CASE(FindNode) { Node* head = TestList(); Node* tgt = FindANode(head, 3); // should fail //BOOST_CHECK_EQUAL(tgt->data, 11); // should pass BOOST_CHECK_EQUAL(tgt->data, 3); DelList(head); } BOOST_AUTO_TEST_CASE(AddToEnd) { Node* head = TestList(); AddEndNode(head, 11); Node* tgt = FindANode(head, 11); // should fail //BOOST_CHECK(tgt->next); // should pass BOOST_CHECK(!tgt->next); DelList(head); } BOOST_AUTO_TEST_CASE(AddFront) { Node* head = TestList(); InsertFront(&head, 11); Node* tgt = FindANode(head, 11); // should fail //BOOST_CHECK_EQUAL(tgt->data, 20); // should pass BOOST_CHECK_EQUAL(tgt, head); DelList(head); } BOOST_AUTO_TEST_CASE(DelNode) { Node* head = TestList(); DeleteNode(head, 11); // should fail //BOOST_CHECK(FindANode(head, 3) == nullptr); // should pass BOOST_CHECK(FindANode(head, 11) == nullptr); DelList(head); } // sorted item added to head of list BOOST_AUTO_TEST_CASE(AddSortedHead) {
  • 8. Node* head = TestList(); AddSortedNode(head, 0); // should fail //BOOST_CHECK_EQUAL(head->data, 3); // should pass BOOST_CHECK(head->data == 0); DelList(head); } // sorted item added to mid of list BOOST_AUTO_TEST_CASE(AddSortedMid) { Node* head = TestList(); AddSortedNode(head, 6); Node* prev = head; Node* newNode = FindANode(head, 6); // find newNode->previous while (prev->next->data < newNode->data) prev = prev->next; // check if newNode is mid list BOOST_CHECK(prev->data <= newNode->data); BOOST_CHECK(newNode->next); DelList(head); } // sorted item added to end of list BOOST_AUTO_TEST_CASE(AddSortedEnd) { Node* head = TestList(); AddSortedNode(head, 60); Node*prev = head; Node* newNode = FindANode(head, 60); // find newNode-previous while (prev->next->data < newNode->data) prev = prev->next; // check newNode is end of list (correctly) BOOST_CHECK(prev->data <= newNode->data); BOOST_CHECK(!newNode->next); DelList(head); } BOOST_AUTO_TEST_CASE(SplitList) { Node* head = TestList(); Node* ltList = nullptr; Node* gtList = nullptr; // create 2 new lists from first list
  • 9. Split(head, 3, &ltList, &gtList); Node* ltEnd = ltList; while (ltEnd->next) ltEnd = ltEnd->next; BOOST_CHECK(ltEnd->data < gtList->data); DelList(head); delete ltList; delete gtList; } BOOST_AUTO_TEST_CASE(RevList) { Node* head = TestList(); ReverseList(&head); // should fail //BOOST_CHECK_EQUAL(head->data, 0); // should pass BOOST_CHECK_EQUAL(head->data, 7); BOOST_CHECK_EQUAL(head->next->data, 3); BOOST_CHECK_EQUAL(head->next->next->data, 0); DelList(head); } BOOST_AUTO_TEST_CASE(SortAsc) { Node* head = TestList(); int tmp = head->data; // change list to 3, 7, 0 head->data = head->next->data; head->next->data = tmp; tmp = head->next->data; head->next->data = head->next->next->data; head->next->next->data = tmp; // change back to 0, 3, 7 SortListAscending(head, head); // should fail //BOOST_CHECK_EQUAL(head->data, 3); // should pass BOOST_CHECK_EQUAL(head->data, 0); BOOST_CHECK_EQUAL(head->next->data, 3); BOOST_CHECK_EQUAL(head->next->next->data, 7); DelList(head); } BOOST_AUTO_TEST_CASE(CheckCircular) {