链表的学习

链表有节点组成,所以要创建链表,先创建节点。
节点分为:数据域、指针域。
创建链表时通常先创建一个空节点作为头节点,因为对链表操作时需要用到头结点,所以头结点一般不动,为一个固定点,好让链表操作容易。
如下: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;
    
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值