zoukankan      html  css  js  c++  java
  • 1 线性表

    1 线性表的链式存储

    1.1 单链表

    1 class Node
    2 {
    3     int value;  /* 数据域 */
    4     Node next;  /* 地址域 */
    5     public Node(int value)
    6     {
    7         this.value = value;
    8     }
    9 }
    定义

     1.2 单链表反转:例如 1→2→3→4→5,反转之后返回 5→4→3→2→1

     1 public static Node reverseNode(Node head)
     2 {
     3     if(head == null || head.next == null)  /* 如果链表为空或只有一个节点,直接返回原链表表头 */
     4         return head;
     5     Node current = head;
     6     Node newHead = null;
     7     while( current != null)
     8     {
     9         Node reCurrent = current;
    10         current = current.next;
    11         reCurrent.next = newHead;
    12         newHead = reCurrent;
    13     }
    14     return newHead;
    15 }
    单链表反转

    算法思想:

    1. 从头到尾遍历原链表,每遍历一个结点

    2. 将其摘下放在新链表的最前端

    3. 注意链表为空和只有一个结点的情况

    1.3 合并两个有序的单链表:例如 1→3→5 和 2→4→6 合并之后为 1→2→3→4→5→6

    算法思想:

    1. 通过比较确定新链表的第一个结点

    2. 移动链表1或者链表2的头指针

    3. 通过递归得到新链表第一个结点的next 

     1 public static Node mergeList(Node head1, Node head2)
     2 {
     3     if(head1 == null)
     4         return head2;
     5     if(head2 == null)
     6         return head1;
     7     Node newHead;
     8     if(head1.value < head2.value)
     9     {
    10         newHead = head1;
    11         head1 = head1.next;
    12     }else
    13     {
    14         newHead = head2;
    15         head2 = head2.next;
    16     }
    17     newHead.next = mergeList(head1, head2);
    18     return newHead;
    19 }
    合并两个有序的单链表
  • 相关阅读:
    【转载】opencvVS2019配置方法
    windows.h头文件中改变光标位置的函数——SetConsoleCursorPosition
    五行代码解决猴子选大王问题
    AtCoder Beginner Contest 192
    ACM做题注意事项
    数据库部分重点
    数据库7-11章期末复习
    数据库4-6章期末复习
    数据库1-3章期末复习
    ICPC Central Russia Regional Contest (CRRC 19)
  • 原文地址:https://www.cnblogs.com/sketeton/p/11679199.html
Copyright © 2011-2022 走看看