Created
February 14, 2019 14:55
-
-
Save joeke80215/c3a257aee91650f77a39430999faae6d to your computer and use it in GitHub Desktop.
single Link with C
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 <stdlib.h> | |
#include <stdlib.h> | |
struct LinkNode | |
{ | |
int Val; | |
struct LinkNode *Next; | |
}; | |
static int count; | |
void addEnd(struct LinkNode *root,int val); | |
void removeEnd(struct LinkNode *root); | |
struct LinkNode* reverse(struct LinkNode *root); | |
void display(struct LinkNode *root); | |
/* | |
output: | |
0 -> 1 -> 2 -> 3 | |
3 -> 2 -> 1 -> 0 | |
3 -> 2 -> 1 | |
*/ | |
int main(void) | |
{ | |
struct LinkNode *root = (struct LinkNode*)malloc(sizeof(struct LinkNode)); | |
count = 0; | |
root->Val = 0; | |
addEnd(root,1); | |
addEnd(root,2); | |
addEnd(root,3); | |
display(root); | |
root = reverse(root); | |
display(root); | |
removeEnd(root); | |
display(root); | |
getchar(); | |
} | |
void addEnd(struct LinkNode *root,int val) | |
{ | |
struct LinkNode *cur,*newNode; | |
cur = root; | |
newNode = (struct LinkNode*)malloc(sizeof(struct LinkNode)); | |
newNode->Val = val; | |
for(size_t i = 0; i < count; i++) | |
{ | |
cur = cur->Next; | |
} | |
cur->Next = newNode; | |
count++; | |
} | |
void removeEnd(struct LinkNode *root) | |
{ | |
struct LinkNode *cur; | |
cur = root; | |
for(size_t i = 0; i < count; i++) | |
{ | |
cur = cur->Next; | |
} | |
count--; | |
free(cur); | |
} | |
struct LinkNode* reverse(struct LinkNode *root) | |
{ | |
struct LinkNode *prev,*cur,*next; | |
cur = root; | |
for(size_t i = 0; i < count + 1; i++) | |
{ | |
next = cur->Next; | |
cur->Next = prev; | |
prev = cur; | |
cur = next; | |
} | |
return prev; | |
} | |
void display(struct LinkNode *root) | |
{ | |
struct LinkNode *cur; | |
cur = root; | |
for(size_t i = 0; i < count + 1; i++) | |
{ | |
if (i == count) { | |
printf("%d\n",cur->Val); | |
} else | |
{ | |
printf("%d -> ",cur->Val); | |
} | |
cur = cur->Next; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment