java 链表相加_java算法之链表两数相加

/***

给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。 你可以假设除了数字 0

之外,这两个数字都不会以零开头。 示例: 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 +

465 = 807

@author 96414

*/

class ListNode {

public int val;

public ListNode next;

}

public class ListNodeTest {

ListNode head; // 链表的表头指针

public ListNode init() {

head = new ListNode();

head.next = null;

return head;

}// 初始化

public void add(int x) { // 将x加入升序链表

ListNode pre, p, q;

// for (pre = head, p = head.next; p != null; p = p.next, pre = pre.next)

// if (p.val > x)

// break;

pre = head;

p = head.next;

q = new ListNode();

q.val = x;

q.next = p;

pre.next = q; // 将q插入到pre和p之间

}

public ListNode find(int x) {// 在表中重找x,找到则返回其前驱结点的指针,找不到则返回null

ListNode pre, p;

pre = head;

p = head.next;

while (p != null && p.val != x) {

pre = pre.next;

p = p.next;

}

if (p == null)

return null;

return pre;

}

public void del(int x) {// 从链表中删除值为x的元素

ListNode pre = find(x);

if (pre == null)

return; // 没找到

else

pre.next = pre.next.next; // 实施删除

}

public void showInfo() {

for (ListNode p = head.next; p != null; p = p.next)

System.out.print(p.val + " ");

}

public static void main(String[] args) {

ListNodeTest test = new ListNodeTest();

ListNodeTest test2 = new ListNodeTest();

ListNode l1 = test.init();

ListNode l2 = test2.init();

System.out.print("请输入一组数,以-1结束:");

Scanner sc = new Scanner(System.in);

int x = sc.nextInt();

while (x != -1) {

test.add(x);

x = sc.nextInt();

}

int y = sc.nextInt();

while (y != -1) {

test2.add(y);

y = sc.nextInt();

}

System.out.print("有序链表l1为:");

test.showInfo();

System.out.println();

System.out.print("有序链表l2为:");

test2.showInfo();

System.out.println();

System.out.println("结果为:");

addTwoNumbers(l1.next, l2.next);

}

public static void addTwoNumbers(ListNode l1, ListNode l2) {

ListNode dummyHead = new ListNode();

dummyHead.next=null;

dummyHead.val=0;

ListNode p = l1, q = l2, curr = dummyHead;

int carry = 0;

while (p != null || q != null) {

int x = (p != null) ? p.val : 0;

int y = (q != null) ? q.val : 0;

System.out.println(p.val);

System.out.println(q.val);

int sum = carry + x + y;

carry = sum / 10;

curr.next = new ListNode();

curr.next.val = sum % 10;

curr = curr.next;

if (p != null) p = p.next;

if (q != null) q = q.next;

}

if (carry > 0) {

curr.next = new ListNode();

curr.next.val = carry;

}

for (ListNode x1 = dummyHead.next; x1 != null; x1 = x1.next) {

System.out.print(x1.val + " ");

}

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值