链表反转:
思路采用栈,而栈可以用slice的思路实现
Go版本
func reverseList(head *ListNode) *ListNode {
// 数组slice当作stack
stack:=[]int{}
for head!=nil{
stack=append(stack,head.Val);
head=head.Next
}
if len(stack)==0{
return nil
}
ans:=&ListNode{Val:stack[len(stack)-1]};
res:=ans;
stack=stack[:len(stack)-1]
for len(stack)>0{
temp:=stack[len(stack)-1]
stack=stack[:len(stack)-1]
node:=&ListNode{Val:temp}
res.Next=node
res=res.Next
}
return ans;
}
链表两数相加:
纯粹的反转相加,注意考虑类似于l1=[5],l2=[5]的情况
Go版本
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
// l1,l2非空链表反转
l1_reverse,l1_count:=reverse(l1);
l2_reverse,l2_count:=reverse(l2);
ans:=&ListNode{Val:0}
res:=ans;
min_count:=0;
// 计算链表长度
if l1_count>l2_count{
min_count=l2_count
// max_count=l1_count;
}else{
min_count=l1_count
// max_count=l2_count-l1_count;
}
temp:=0 //表示进
for min_count>0{
Value:=l1_reverse.Val+l2_reverse.Val+temp
temp=0;
if Value>=10{
Value=Value-10;
temp=1;
}else{
Value=Value;
}
// fmt.Print(l1_reverse.Val,l2_reverse.Val,Value)
// fmt.Println()
node:=&ListNode{Val:Value}
l1_reverse=l1_reverse.Next
l2_reverse=l2_reverse.Next
res.Next=node;
res=res.Next;
min_count--;
l1_count--;
l2_count--;
}
LastNode:=&ListNode{}
if l1_count!=0{
LastNode=l1_reverse;
}else{
LastNode=l2_reverse;
}
for LastNode!=nil || temp!=0{
if LastNode==nil{
LastNode=&ListNode{Val:0};
}
Value:=LastNode.Val+temp
temp=0;
if Value>=10{
Value=Value-10;
temp=1;
}else{
Value=Value;
}
node:=&ListNode{Val:Value}
res.Next=node;
res=res.Next;
LastNode=LastNode.Next
}
ans_reverse,_:=reverse(ans.Next)
return ans_reverse;
}
func reverse(head *ListNode)(*ListNode,int){
stack:=[]int{};
count:=0
for head!=nil{
stack=append(stack,head.Val)
head=head.Next
count++;
}
ans:=&ListNode{Val:stack[len(stack)-1]}
stack=stack[:len(stack)-1]
res:=ans;
for(len(stack)>0){
node:=&ListNode{Val:stack[len(stack)-1]}
stack=stack[:len(stack)-1]
res.Next=node
res=res.Next
}
return ans,count;
}
网友评论