golang实现反转链表

反转链表

Posted by 果果 on November 23, 2022

golang实现反转链表

位置调换次数 pre cur whole
0 nil 1->2->3->4->5 1->2->3->4->5
1 1->nil 2->-3>->4->5 2->3->4->5->1->nil
2 2->1->nil 3->4->5 3->4->5->2->1->nil
3 3->2->1->nil 4->5 4->5->3->2->1->nil
4 4->3->2->1->nil 5 5->4->3->2->1->nil
package main

import "fmt"

//链表节点
type ListNode struct {
	Val  int
	Next *ListNode
}

//反转链表的实现
func reverseListV1(head *ListNode) *ListNode {
	if head == nil {
		return nil
	}

	var newHead *ListNode
	for head != nil {
		node := head.Next
		head.Next = newHead
		newHead = head
		head = node
	}

	return newHead
}
func reverseListV2(head *ListNode) *ListNode {
	if head == nil {
		return nil
	}

	var newHead *ListNode
	for head != nil {
		head.Next, newHead, head = newHead, head, head.Next
	}

	return newHead
}

func main() {
	head := new(ListNode)
	head.Val = 1
	ln2 := new(ListNode)
	ln2.Val = 2
	ln3 := new(ListNode)
	ln3.Val = 3
	ln4 := new(ListNode)
	ln4.Val = 4
	ln5 := new(ListNode)
	ln5.Val = 5
	head.Next = ln2
	ln2.Next = ln3
	ln3.Next = ln4
	ln4.Next = ln5

	//pre := reverseListV1(head)
	//fmt.Println(pre)
	pre2 := reverseListV2(head)
	fmt.Println(pre2)
}