-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathList.cpp
More file actions
96 lines (85 loc) · 1.35 KB
/
List.cpp
File metadata and controls
96 lines (85 loc) · 1.35 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
//list
//todo: size, remove
#include "stdafx.h"
#include<iostream>
using namespace std;
struct ListNode
{
int value;
ListNode* next;
ListNode(int x) : value(x), next(NULL) {}
};
struct List
{
friend void print(ostream& os, List* L);
public:
List() : head(new ListNode(0)), tail(NULL) {}
~List();
void insertHead(int x);
void insertTail(int x);
private:
ListNode* head;
ListNode* tail;
};
void List::insertHead(int x)
{
ListNode* newp = new ListNode(x);
newp->next = head->next;
head->next = newp;
if (tail == NULL)
tail = newp;
}
List::~List()
{
ListNode* tmp = head->next;
if (tmp != NULL)
{
ListNode* t = tmp->next;
delete tmp;
tmp = t;
}
delete head;
}
void print(ostream& os, List* L)
{
if (L->head->next == NULL)
{
os << "the list is empty" << endl;
}
ListNode* tmp = L->head->next;
while (tmp != NULL)
{
os << tmp->value << " ";
tmp = tmp->next;
}
os << endl;
}
void List::insertTail(int x)
{
ListNode* newp = new ListNode(x);
if (tail == NULL)
{
tail = newp;
head->next = newp;
return;
}
tail->next = newp;
tail = newp;
if (head->next == NULL)
head->next = tail;
}
int main(int argc, char* argv)
{
List *L = new List();
L->insertTail(4);
L->insertHead(1);
L->insertHead(2);
L->insertHead(3);
L->insertTail(4);
L->insertTail(5);
L->insertHead(6);
print(cout, L);
delete L;
system("pause");
return 0;
}