链表常用操作 (定义,创建,反转,合并,交叉)

来源:互联网 发布:大地彩票v6 源码 编辑:程序博客网 时间:2024/05/19 01:59

 struct Node{
    int data;
    Node *next;
};

 

//头插入法

Node* _link_create_head()
{
    cout<<"create link head"<<endl;

    Node *head=NULL;
    Node *p;

    for(int i=0;i<=5;i++)
    {
        p=(Node*)malloc(sizeof(Node*));
        p->data=i;
        p->next=head;
        head=p;
    }
    return head;
}

 

//反转

Node* reveseLinkList(Node* head)
{
    Node *p1=head, *p2=NULL, *p3=NULL;//用p2反指向p1,p3作为p2的next的记录
    if(p1==NULL) return NULL;
    p2=p1->next;
    while(p2 != NULL)
    {
        p3=p2->next;
        p2->next=p1;
        p1=p2;//前移
        p2=p3;//前移
    }
    head->next=NULL;//头变成尾
    return p1;
}

 

//合并

---------一般合并

Node* mergeLinkList(Node* head1, Node* head2)
{
    Node *cur1=head1, *cur2=head2, *cur=NULL, *ret;
    int i=1;
    while(cur1 && cur2)
    {
        if(cur1->data < cur2->data)//cur1 小,cur1下走,cur为cur1,cur->next即为cur1->next
        {
            if(cur==NULL)
            {
                cur=cur1;
                ret=cur;
                cur1=cur1->next;
                cout<<"cur1< && NULL"<<endl;
            }
            else
            {
                cur->next=cur1;
                cur=cur->next;
                cur1=cur1->next;
                cout<<"cur1< && NOTNULL"<<endl;
            }
        }
        else//cur2小,cur->next=cur2,cur2下走
        {
             if(cur==NULL)
             {
                cur=cur2;
                ret=cur;
                cur2=cur2->next;
                cout<<"cur2< && NULL"<<endl;
             }
            else
            {
                cur->next=cur2;//cur1指向cur2的节点
                cur=cur->next;
                cur2=cur2->next;//cur2向下走
                cout<<"cur2< && NOTNULL"<<endl;
            }
        }
        cout<<"*******"<<i<<"******"<<endl;
        i++;
    }
    if(cur1)
        cur->next=cur1;
    else
        cur->next=cur2;

    return ret;
}

---------递归合并

Node * MergeRecursive(Node *head1 , Node *head2)
{
    if ( head1 == NULL )
        return head2 ;
    if ( head2 == NULL)
        return head1 ;
 Node *head = NULL ;
 if ( head1->data < head2->data )
 {
  head = head1 ;
  head->next = MergeRecursive(head1->next,head2);
 }
 else
 {
  head = head2 ;
  head->next = MergeRecursive(head1,head2->next);
 }
 return head ;
}

原创粉丝点击