两数之差(链表实现)面试算法题——字节跳动
字节跳动客户端一面遇到的算法题
由于是第一次,面试时有点小紧张,上来就给我整了一道手撕算法,着实有点懵,想了很久都没有思路....
过了几天才想着要把这道题解决,实在是懒狗捏
https://www.nowcoder.com/discuss/694139?source_id=profile_create_nctrack&channel=-1
参考题目:两数之和 https://leetcode-cn.com/problems/add-two-numbers/
package LeetCode.字节跳动面试题.大数之差链表版;
import java.util.ArrayList;
/*
两个大数之差 链表版
两个链表 分别存放两个大数,头部放最高位,尾部放最低位,
求这两个数的差
*/
public class Solution {
public static void main(String[] args) {
int[] nums1 = {6,9};
int[] nums2 = {5,5,7};
int len_1 = nums1.length;
int len_2 = nums2.length;
ListNode head1 = addListNode(nums1);
ListNode head2 = addListNode(nums2);
if (len_1 > len_2) { // 大数减小数
System.out.println(listToArrayList(head1));
System.out.print("- ");
System.out.println(listToArrayList(head2));
System.out.println(listToArrayList(minusInList(head1, head2)));
}else { // 小数减大数
System.out.println(listToArrayList(head1));
System.out.print("- ");
System.out.println(listToArrayList(head2));
System.out.println("- " + listToArrayList(minusInList(head2, head1)));
}
}
public static ListNode minusInList(ListNode head1, ListNode head2) {
ListNode ans = new ListNode(-1);
ListNode p = ans; // ans 是头节点
int pre = 0; // 表示借位
// 反转链表 从尾部往前计算每一位的差值
head1 = reverse(head1);
head2 = reverse(head2);
while (head1 != null && head2 != null) {
int differ = head1.val - head2.val + pre;
pre = differ < 0 ? -1 : 0;
if (differ<0) {
differ = (differ + 10) % 10;
}
p.next = new ListNode(differ);
p = p.next;
head1 = head1.next;
head2 = head2.next;
}
while (head1 != null) {
int differ = head1.val+ pre;
pre = differ < 0 ? -1 : 0;
if (differ<0) {
differ = (differ + 10) % 10;
}
p.next = new ListNode(differ);
p = p.next;
head1 = head1.next;
}
while (head2 != null) {
int differ = head2.val + pre;
pre = differ < 0 ? -1 : 0;
if (differ<0) {
differ = (differ + 10) % 10;
}
p.next = new ListNode(differ);
p = p.next;
head2 = head2.next;
}
// 反转链表
return reverse(ans.next);
}
public static ListNode reverse(ListNode head) { // 实现反转链表
ListNode pre = null;
while (head != null) {
ListNode next = head.next;
head.next = pre;
pre = head; // 这里容易写错!
head = next;
}
return pre;
}
public static ArrayList<Integer> listToArrayList(ListNode head) { // 将链表转化为数组
ArrayList<Integer> list = new ArrayList<Integer>();
if (head == null) {
return list;
}
while (head != null) {
list.add(head.val);
head = head.next;
}
return list;
}
public static ListNode addListNode(int[] nums) { // 根据数组来建立链表
ListNode head = new ListNode(-1);
ListNode temp = null;
temp = head;
for (int i = 0; i < nums.length; i++) {
temp.next = new ListNode(nums[i]);
temp = temp.next;
/* System.out.print("nums[" + i + "]: "+nums[i] + " temp.val : ");
System.out.println(temp.val);*/
}
return head.next; // 返回该链表的头节点
}
}
class ListNode {
int val;
ListNode next = null;
public ListNode(int val) {
this.val = val;
}
}
本文来自博客园,作者:{夕立君},转载请注明原文链接:https://www.cnblogs.com/xili-sanriyue/p/15088179.html