1、题目
2、解题1
申请空间解法
package main
import . "nc_tools"
/*
* type ListNode struct{
* Val int
* Next *ListNode
* }
*/
/**
*
* @param head ListNode类
* @return void
*/
func reorderList( head *ListNode ) {
// write code here
if head == nil{
return
}
var stk []*ListNode
var tmp *ListNode
tmp = head
for tmp != nil{
tmp2 := tmp.Next
tmp.Next = nil
stk = append(stk, tmp)
tmp = tmp2
}
i := len(stk)-1
j := 0
for j<i{
stk[j].Next = stk[i]
if j+1 == i{
break
}
stk[i].Next = stk[j+1]
i--
j++
}
head = stk[0]
return
}
3、解题2
不申请空间解法
package main
import . "nc_tools"
/*
* type ListNode struct{
* Val int
* Next *ListNode
* }
*/
/**
*
* @param head ListNode类
* @return void
*/
func reorderList( head *ListNode ) {
// write code here
if head == nil{
return
}
//获取长度
nodeLen := 0
tmp := head
for tmp != nil{
nodeLen++
tmp = tmp.Next
}
//截断
tmp = head
for i:= 0;i< (nodeLen-1)/2;i++{
tmp = tmp.Next
}
head1 := head
head2 := tmp.Next
tmp.Next = nil
//翻转
var first *ListNode
var second *ListNode
var third *ListNode
first = nil
second = head2
for second != nil{
third = second.Next
second.Next = first
first = second
second = third
}
//合并
head2 = first
for head1 != nil && head2 != nil{
tmp = head1.Next
tmp2 := head2.Next
head1.Next = head2
head2.Next = tmp
head1 = tmp
head2 = tmp2
}
}