java链表是创建和使用

java链表

在java中要自定义一个链表类

class ListNode{
	int val;
	ListNode next;
	ListNOde(int x) {val = x;}
}

题目1:从未到头打印一个链表。

方法:递归法先递推至链表末端,回溯时,依次将节点加入列表。

终止条件:head==None。

递推:访问下一个节点head.next;

回溯:将head.val加入列表。

class Solution {
    ArrayList<Integer> tmp = new ArrayList<Integer>();
    public int[] reversePrint(ListNode head) {
        recur(head);
        int[] res = new int[tmp.size()];
        for(int i = 0; i < res.length; i++)
            res[i] = tmp.get(i);
        return res;
    }
    void recur(ListNode head) {
        if(head == null) return;
        recur(head.next);
        tmp.add(head.val);
    }
}

题目2

将两个链表数加起来:每个节点只存储一位数字,逆序存储。

如:7->2->3

​ 2->8->2

输出:8->0->6

思路:定位输出从头节点开始两两相加,再把值存入新的链表 节点,满10就进位。

要点:创建一个新链表存储数据,判断进位当最后一个数字大于10需要进位需要再创建一个新节点。

 public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = null, tail = null;//创建两个链表节点为空
        int carry = 0;//用来进位
        while (l1 != null || l2 != null) {
            int n1 = l1 != null ? l1.val : 0;
            int n2 = l2 != null ? l2.val : 0;
            int sum = n1 + n2 + carry;//把两节点的值相加
            if (head == null) {
                head = tail = new ListNode(sum % 10);//head储存tail的头节点数据方便访问数据
            } else {
                tail.next = new ListNode(sum % 10);
                tail = tail.next;//用tail去建立链表
            }
            carry = sum / 10;
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        if (carry > 0) {
            tail.next = new ListNode(carry);//判断最后一位是否需要进位
        }
        return head;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值