Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "stdio.h"
- #include "malloc.h"
- struct Node{
- int value;
- Node *next, *prev;
- }*head, *tail, *current;
- Node* createNode(int value){
- Node* temp = (Node*)malloc(sizeof(Node));
- temp->value = value;
- temp->prev = temp->next = NULL;
- return temp;
- }
- int TOTAL_DATA = 0;
- void pushHead(int value){
- current = createNode(value);
- if( !head ){
- head = tail = current;
- }else{
- current->next = head;
- head->prev = current;
- head = current;
- }
- ++TOTAL_DATA;
- }
- void pushTail(int value){
- current = createNode(value);
- if( !head ){
- head = tail = current;
- }else{
- tail->next = current;
- current->prev = tail;
- tail = current;
- }
- ++TOTAL_DATA;
- }
- void pushMidByIndex(int index, int value){
- if( index < 0 || index > TOTAL_DATA ) return;
- if( index == 0 ) pushHead(value);
- else if( index == TOTAL_DATA ) pushTail(value);
- else{
- Node* find = head;
- current = createNode(value);
- for(int i=1;i<index;++i) find = find->next;
- current->next = find->next;
- find->next->prev = current;
- find->next = current;
- current->prev = find;
- ++TOTAL_DATA;
- }
- }
- void popHead(){
- if( !head ) return;
- if( head == tail ){
- free(head);
- head = tail = NULL;
- --TOTAL_DATA;
- return;
- }
- current = head;
- head = head->next;
- free(current);
- head->prev = current = NULL;
- --TOTAL_DATA;;
- }
- void popTail(){
- if( !head ) return;
- if( head == tail ){
- free(head);
- head = tail = NULL;
- --TOTAL_DATA;
- return;
- }
- current = tail;
- tail = tail->prev;
- free(current);
- tail->next = current = NULL;
- --TOTAL_DATA;
- }
- void popMidByIndex(int index){
- if( index < 0 || index > TOTAL_DATA-1 ) return;
- if( head == tail ){
- free(head);
- head = tail = NULL;
- --TOTAL_DATA;
- return;
- }
- Node* find = head;
- for(int i = 0 ; i < index; ++i) find = find->next;
- find->prev->next = find->next;
- find->next->prev = find->prev;
- free(find);
- find = NULL;
- --TOTAL_DATA;
- }
- void popAll(){
- while( head ) popHead();
- }
- int viewAll(){
- current = head;
- while( current ){
- printf("%d ", current->value);
- current = current->next;
- }
- }
- int main(){
- pushMidByIndex(0,1);
- pushMidByIndex(0,2);
- pushMidByIndex(0,3);
- pushMidByIndex(0,4);
- pushMidByIndex(0,5);
- popMidByIndex(2);
- pushMidByIndex(2,100);
- viewAll();
- getchar();
- return 0;
- }
Add Comment
Please, Sign In to add comment