给一个单向链表,从链表尾开始每两位翻转,如:
1->2->3->4 翻转后 2->1->4->3
1->2->3->4->5 翻转后 1->3->2->5->4
题解,单向链表,肯定只能从头开始遍历。根据题目描述,每两位翻转,所以这里要区分链表长度奇偶性,偶数很简单,从头开始,每两位翻转即可。奇数,第一位不变,后面的链表和偶数处理方式一致。
type node struct {
value int
next *node
}
func revert(head *node) *node {
var count int
cur := head
for cur != nil {
count++
cur = cur.next
}
if count%2 == 0 {
return revert2(head)
}
head.next = revert2(head.next)
return head
}
// 翻转链表,链表必须是偶数长度
func revert2(head *node) *node {
if head == nil || head.next == nil {
return head
}
next := head.next
next2 := next.next
// 链表第二个节点指向第一个节点
next.next = head
// 链表的第一节点指向第三个节点,第三个节点以及后面的节点递归走翻转逻辑
head.next = revert2(next2)
return next
}