代码改变世界

链表基础操作

2013-02-04 17:10  littlelion  阅读(159)  评论(0编辑  收藏  举报

链表的操作,包括创建,查找,插入,删除。

  1 struct node{
  2     int data;
  3     node* next;
  4 };
  5 
  6 void createList(node* head,int var)
  7 {
  8     node* current_node = head;
  9     node* next_node = new node();
 10     next_node->data = var;
 11     next_node->next = NULL;
 12     while(current_node->next!=NULL){
 13         current_node = current_node->next;
 14     }
 15     current_node->next = next_node;
 16 }
 17 
 18 void ergodicList(node* head)
 19 {
 20     node* current_node = head;
 21     while(current_node->next!=NULL)
 22     {
 23         current_node = current_node->next;
 24         printf("current node's value is %d\n",current_node->data);
 25     }
 26 }
 27 
 28 void searchElementInList(node* head,int var)
 29 {
 30     node* current_node = head;
 31     if(current_node == NULL)
 32     return;
 33     else
 34     {
 35         while(current_node->data!=var && current_node->next!=NULL)
 36         {
 37             current_node = current_node->next;
 38         }
 39         if(current_node->data == var)
 40         {
 41             printf("got element %d\n",current_node->data);
 42         }
 43         else
 44         {
 45             printf("could not find element %d\n",var);
 46         }    
 47     }
 48 }
 49 
 50 void insertElementInList(node* head,int varAt,int element)
 51 {
 52     node* current_node = head;
 53     node* insert_node = new node();
 54     insert_node->data = element;
 55     insert_node->next = NULL;
 56     if(current_node == NULL)
 57     return;
 58     else
 59     {
 60         while(current_node->data!=varAt && current_node->next!=NULL)
 61         {
 62             current_node = current_node->next;
 63         }
 64         if(current_node->data == varAt)
 65         {
 66             node* next_node = current_node->next;
 67             current_node->next = insert_node;
 68             insert_node->next = next_node;
 69         }
 70     }
 71 }
 72 
 73 void deleteElementFromList(node* head,int var)
 74 {
 75     node* current_node = head;
 76     node* pre_node;
 77     if(current_node == NULL)
 78     return;
 79     else
 80     {
 81         if(current_node->data == var)
 82         {
 83             head = current_node->next;
 84             delete current_node;
 85         }
 86         else
 87         {
 88             while(current_node->data!=var && current_node->next!=NULL)
 89             {
 90                 pre_node = current_node;
 91                 current_node = current_node->next;
 92             }
 93             if(current_node->data == var)
 94             {
 95                 pre_node->next = current_node->next;
 96                 delete current_node;
 97             }
 98         }
 99     }
100 }