-
Notifications
You must be signed in to change notification settings - Fork 0
/
insert.cpp
42 lines (36 loc) · 1.26 KB
/
insert.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Script que apresenta um exemplo de como inserir um novo nó em uma
* posição específica da lista ligada.
*
* As funções aqui apresentadas poderiam ser métodos das classes criadas
* porém optou-se por manter fora para possibilitar o entendimento do que as
* mudanças feitas em pointeiros podem causar na execução do código.
*/
#include <iostream>
#include "linkedlist.h"
void insertNodeInLinkedList(int position, StringNode * list, StringNode * newNode) {
if (list != NULL) {
if (position == 0) {
newNode->next = list->next;
list->next = newNode;
}
insertNodeInLinkedList(position - 1, list->next, newNode);
}
}
void viewLinkedList(StringNode * list) {
if (list != NULL) {
cout << list->content << endl;
return viewLinkedList(list->next);
}
}
int main(void) {
StringNode * nodeOne = new StringNode("Bom dia");
StringNode * nodeTwo = new StringNode("Boa tarde");
StringNode * nodeThree = new StringNode("Boa noite");
// Vinculando dois nós
nodeOne->next = nodeThree;
viewLinkedList(nodeOne);
// Inserindo um novo nó na posição entre "Bom dia" e "Boa noite"
insertNodeInLinkedList(0, nodeOne, nodeTwo);
viewLinkedList(nodeOne);
}