Go语言每日一练——链表篇(九)

时间:2024-02-16 19:15:15

传送门

牛客面试笔试必刷101题 ----------------链表相加(二)

题目以及解析

题目

在这里插入图片描述

解题代码及解析

解析

这一道题主要是要对链表相加的过程进行模拟,虽然思路不难但是细节出比较多,这里博主的思路主要是先将两个链表反转过来然后以Head1为基础来模拟相加过程,最后将答案链表再反转回来

代码

package main

import (
	_ "fmt"
	. "nc_tools"
)

/*
 * type ListNode struct{
 *   Val int
 *   Next *ListNode
 * }
 */

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param head1 ListNode类
 * @param head2 ListNode类
 * @return ListNode类
 */

func ReserveList(head *ListNode) *ListNode {
	var prev *ListNode = nil
	current := head
	for current != nil {
		next := current.Next
		current.Next = prev
		prev = current
		current = next
	}
	return prev
}

func add(val1, val2, plus int) (int, int) {
	result := val1 + val2 + plus
	if result > 9 {
		plus = 1
	} else {
		plus = 0
	}
	result = result % 10
	return result, plus
}

func addInList(head1 *ListNode, head2 *ListNode) *ListNode {
	Head1 := ReserveList(head1)
	Head2 := ReserveList(head2)
	result := Head1
	var phead *ListNode
	plus := 0
	for Head1 != nil || Head2 != nil {
		if Head1 != nil && Head2 != nil {
			Head1.Val, plus = add(Head1.Val, Head2.Val, plus)
			phead=Head1
			Head1 = Head1.Next
			Head2 = Head2.Next
		} else if Head1 != nil {
			Head1.Val, plus = add(Head1.Val, 0, plus)
			phead.Next= Head1
			Head1 = Head1.Next
			phead = phead.Next
		} else {
			Head2.Val, plus = add(0, Head2.Val, plus)
			phead.Next = Head2
			Head2 = Head2.Next
			phead = phead.Next
		}
	}
	if plus > 0 {
		Node := &ListNode{Val: 1}
		phead.Next = Node
		phead = phead.Next
	}
	return ReserveList(result)
}