zoukankan      html  css  js  c++  java
  • 给单链表加1

    用一个 非空 单链表来表示一个非负整数,然后将这个整数加一。

    你可以假设这个整数除了 0 本身,没有任何前导的 0。

    这个整数的各个数位按照 高位在链表头部、低位在链表尾部 的顺序排列。

    示例:

    输入: [1,2,3]
    输出: [1,2,4]

    解法1:

    public static ListNode plusOne(ListNode head) {
        /*链表翻转*/
        ListNode reverse = reverse(head);
        /*定义一个引用指向翻转后的头*/
        ListNode itr = reverse;
        /*进位*/
        int add = 0;
        /*个位加1的值*/
        int c = 1;
        ListNode last = null;
        while (itr != null) {
          /*相加后的结果*/
          int addResult = itr.val + add + c;
          /*进位重新置为0*/
          add = 0;
          /*个位加了就不加了*/
          c = 0;
          if (addResult == 10) {
            /*当值为10时当前值置为0,进位加1*/
            itr.val = 0;
            add = 1;
          } else {
            /*赋值*/
            itr.val = addResult;
          }
          /*保存最后一个节点*/
          if (itr.next == null) {
            last = itr;
          }
          /*节点向后移动一个*/
          itr = itr.next;
        }
        if (add > 0) {
          /*当进位不为0时,说明要新增个节点*/
          last.next = new ListNode(add);
        }
        /*再次翻转*/
        return reverse(reverse);
      }
    
      public static ListNode reverse(ListNode head) {
        ListNode pre = null;
        while (head != null) {
          ListNode tmp = head.next;
          head.next = pre;
          pre = head;
          head = tmp;
        }
        return pre;
      }
    View Code

    解法2:

    思路:

    用快指针fast,遍历链表
    fast.val != 9,慢指针移动到当前快指针处
    fast.val = 9,慢指针原地不动
    遍历结束,慢指针的值加一,慢指针后续所有节点值设置为0,打完收工!

    public ListNode PlusOne(ListNode head)
            {
                //1.双指针
                ListNode fast = head;
                ListNode slow = new ListNode(0);
                slow.next = head;
    
                //2.遍历链表
                while (fast != null)
                {
                    if (fast.val != 9)
                    {
                        slow = fast;
                    }
                    fast = fast.next;
                }
    
                //3.末位加1
                slow.val += 1;
                ListNode cur = slow.next;
                while (cur != null)
                {
                    cur.val = 0;
                    cur = cur.next;
                }
                return slow.next == head ? slow : head;
            }
    View Code

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/plus-one-linked-list

  • 相关阅读:
    Promise 对象
    [转] LVM分区在线扩容
    [转] 打开 CMD 时自动执行命令
    [转] FFmpeg常用基本命令
    systemd 之 journalctl
    systemd 之 systemctl
    关于用户权限的加强与理解(上)
    [转] 测试环境下将centos6.8升级到centos7的操作记录
    [搞机] 双网卡做数据均衡负载
    [转] 网络基础知识1:集线器,网桥,交换机
  • 原文地址:https://www.cnblogs.com/wuyouwei/p/11817176.html
Copyright © 2011-2022 走看看