链表的学习

来源:互联网 发布:js获取list长度 编辑:程序博客网 时间:2024/05/18 22:16
链表有节点组成,所以要创建链表,先创建节点。
节点分为:数据域、指针域。
创建链表时通常先创建一个空节点作为头节点,因为对链表操作时需要用到头结点,所以头结点一般不动,为一个固定点,好让链表操作容易。
如下:struct node * head ;
          head = (struct node *)malloc(sizeof(struct node));
          head->next = NULL;
          
插入节点时,要看清位置,一般分为,插入首节点,在中间插入一个节点,插入尾节点
删除节点时,也分为:首节点,链表中间,尾节点
链表逆序  见:http://blog.csdn.net/yeyuangen/article/details/7359099
下面为一个练习:

#include <stdio.h>#include <stdlib.h>struct node{    int data;    struct node *next;};struct node * head ;struct node * last;void create(void){   // struct node *head;   head = (struct node *)malloc(sizeof(struct node));    head->next = NULL;    last = head;    }void insert( int num)                                                  //创建链表{    struct node * NewNode = (struct node *)malloc(sizeof(struct node));    last -> next = NewNode;    NewNode -> data = num;    NewNode->next = NULL ;     last = NewNode ;}void travel()                                                        //遍历{        struct node * NewNode =  head->next;    while(NewNode != NULL)    {        printf("%d ",NewNode -> data ); NewNode = NewNode -> next;    }    printf("\n");}void input(int pos,int val)                                          //插入节点{    int i = 0; struct node *NewNode = head; struct node *New=(struct node *)malloc(sizeof(struct node)); while(i < pos-1) {     i++;  NewNode = NewNode->next; } New->data = val; New->next = NewNode->next; NewNode->next = New;  }void del(void)                                                      //删除节点的数值为奇数的节点{   struct node *NewNode = head;   struct node *temp = NewNode->next;   while( NewNode != last)   {              if( (temp->data) % 2 != 0)       {          // printf("%d\n",temp->data);          if( temp != last)         {               NewNode->next = temp->next;            free(temp);            temp = NULL;         }        else        {            NewNode->next =NULL;            free(last);            break;         }   temp = NewNode->next;       }    else    {            NewNode = NewNode->next;   temp = NewNode->next;  }    }   }void reverse()                                                        //逆序{    struct node *t =NULL;    struct node *p =head->next;    struct node *q =head->next->next;    if(head->next ==NULL || head->next->next==NULL)    {        printf("empty or only one\n");    }    while(q != NULL)    {        t = q->next; q->next = p; p = q; q = t;    }    head->next->next =NULL;    head->next = p;}int main(){    int i;    create();    for( i = 0 ; i < 10; i++ )    {        insert(i);    }    travel(); input(3,5); travel();    del();      travel();   // reverse();   // travel();    return 0;    }


0 0
原创粉丝点击