(链表)11-链表相加

 

 

 1 import java.util.*;
 2 
 3 /*
 4  * public class ListNode {
 5  *   int val;
 6  *   ListNode next = null;
 7  * }
 8  */
 9 
10 public class Solution {
11     /**
12      *
13      * @param head1 ListNode类
14      * @param head2 ListNode类
15      * @return ListNode类
16      */
17     public ListNode addInList (ListNode head1, ListNode head2) {
18         // 翻转两个入参链表
19         head1 = reverseList(head1);
20         head2 = reverseList(head2);
21         // 创建新链表作为返回结果
22         ListNode root = new ListNode(-1);
23         ListNode current = root;
24         // 进位符号
25         int flag = 0;
26         // 依次相加
27         while(head1 != null || head2 != null || flag != 0) {
28             // 计算当前位的结果
29             int val1 = (head1 == null) ? 0 : head1.val;
30             int val2 = (head2 == null) ? 0 : head2.val;
31             int temp = val1 + val2 + flag;
32             flag = temp / 10;
33             temp = temp % 10;
34             // 返回结果中增加新的节点
35             ListNode newNode = new ListNode(temp);
36             current.next = newNode;
37             current = current.next;
38             // 移动到下一位进行计算
39             if (head1 != null) {
40                 head1 = head1.next;
41             }
42             if (head2 != null) {
43                 head2 = head2.next;
44             }
45         }
46         // 返回结果
47         return reverseList(root.next);
48     }
49 
50     public ListNode reverseList(ListNode head) {
51         // 申请临时变量
52         ListNode current = head;
53         ListNode pre = null;
54         // 依次调换指针的方向
55         while (current != null) {
56             // 记录下个要处理的节点
57             ListNode next = current.next;
58             // 调换当前节点的指针方向
59             current.next = pre;
60             // 移动到下个要处理的节点
61             pre = current;
62             current = next;
63         }
64         // 返回调换后的头节点
65         return pre;
66     }
67 }

 

posted @ 2023-11-13 22:58  StringBuilder  阅读(14)  评论(0)    收藏  举报