zoukankan      html  css  js  c++  java
  • 链表常见操作练习

    链表是一个很重要的数据结构,一直没有好好的写过练习,这次放假,

    好好练习一下。

    1、定义链表节点

    #include <stdio.h>
    #include <stdlib.h>
    #include <assert.h>
    typedef struct Int_Node {
        int data; //数据
        struct Int_Node * next; //指向下一个节点
    }Node;

    2、合并两个有序链表

    //版本1

    Node* Merge(Node *p, Node *q){
        Node *head, *tmp;
        assert(p && q);
        if(p->data <= q->data){
            head = tmp = p;
            p = p->next;
        }else{
            head = tmp = q;
            q = q->next;
        }
        while(p && q){
            if(p->data <= q->data){
                tmp->next = p;
                tmp = p;
                p = p->next;
            }else{
                tmp->next = q;
                tmp = q;
                q = q->next;
            }
        }
        if(p){
            tmp->next = p;
        }
        if(q){
            tmp->next = q;
        }
        return head;
    }

    //版本2

    Node* Merge2(Node *p, Node *q){
        Node *head = NULL,
      *tmp = NULL,
      *cur = NULL;
        while(p && q){
            if(p->data <= q->data){
                cur = p;
                p = p->next;
            }else{
                cur = q;
                q = q->next;
            }
            if(NULL == head){
                head = tmp = cur;
            }else{
                tmp->next = cur;
                tmp = cur;
            }
        }
        if(NULL == p){
            tmp->next = q;
        }else{
            tmp->next = p;
        }
        return head;
    }

  • 相关阅读:
    静态主席树
    uva 11107 Life Forms
    codeforce 605B. Lazy Student
    codeforce 606B Testing Robots
    codeforce 606C
    codeforce 606A
    uva 11019 Matrix Matcher
    uva 11468 Substring
    uvalive 4670 Dominating Patterns
    codeforce 603B
  • 原文地址:https://www.cnblogs.com/xkxjy/p/2078107.html
Copyright © 2011-2022 走看看