Created
May 26, 2017 18:09
-
-
Save Zekt/b18d154efda3b481db3038acaedaaa3f to your computer and use it in GitHub Desktop.
資訊之芽 2017 250 Linked-List
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
struct Node { | |
int data; | |
Node* next; | |
}; | |
Node* head; | |
void print_list(); | |
void push_front(int data); | |
void pop_front(); | |
int main() { | |
head = NULL; | |
for (int i = 0; i < 5; i++) { | |
push_front(i); | |
} | |
print_list(); | |
for (int i = 0; i < 5; i++) { | |
pop_front(); | |
} | |
print_list(); | |
for (int i = -5; i < 0; i++) { | |
push_front(i); | |
} | |
print_list(); | |
for (int i = 0; i < 4; i++) { | |
pop_front(); | |
} | |
print_list(); | |
} | |
void print_list() { | |
Node* tmp = head; | |
if (head != NULL) | |
std::cout << "head ->\n"; | |
else | |
std::cout << "empty\n"; | |
while(tmp != NULL) { | |
std::cout << tmp->data << std::endl; | |
tmp = tmp->next; | |
} | |
} | |
void push_front(int data) { | |
Node* newHead = new Node; | |
newHead->data = data; | |
newHead->next = head; | |
head = newHead; | |
} | |
void pop_front() { | |
Node* tmp = head; | |
head = head->next; | |
delete tmp; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment