Created
February 14, 2013 07:27
-
-
Save yinyanghu/4951134 to your computer and use it in GitHub Desktop.
Linus's Linked List
This file contains hidden or 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> | |
#include <cstdio> | |
#include <cstring> | |
#include <cstdlib> | |
#include <ctime> | |
using namespace std; | |
typedef struct node | |
{ | |
int key; | |
struct node *next; | |
} node; | |
int N; | |
node *head; | |
void print_list(node *ptr) | |
{ | |
while (ptr != NULL) | |
{ | |
printf("%d", ptr -> key); | |
if (ptr -> next != NULL) | |
printf(" --> "); | |
ptr = ptr -> next; | |
} | |
printf("\n"); | |
} | |
void remove(node **head, int key) | |
{ | |
for (node **cur = head; *cur != NULL; ) | |
{ | |
node *entry = *cur; | |
if (entry -> key == key) | |
{ | |
*cur = entry -> next; | |
free(entry); | |
} | |
else | |
cur = &(entry -> next); | |
} | |
} | |
int main() | |
{ | |
srand(time(NULL)); | |
N = 10; | |
head = NULL; | |
for (int i = 0; i < N; ++ i) | |
{ | |
node *ptr = new(node); | |
ptr -> key = rand() % 100; | |
ptr -> next = head; | |
head = ptr; | |
} | |
print_list(head); | |
while (head != NULL) | |
{ | |
int key; | |
scanf("%d", &key); | |
remove(&head, key); | |
print_list(head); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment