内存地址 链表 指针 反转链表
&e= 0xc00000a080 &f= 0xc00000a088
&e.Next= 0xc0000510c8 &f.Next= 0xc0000510c8
*e= {0 <nil>} *f= {0 <nil>}
0----
&i.Next= 0xc0000510f8
&i= 0xc00000a090 &j= 0xc00000a098 &p= 0xc00000a0a0 &q= 0xc00000a0a8
&(i.Next)= 0xc0000510f8 &(p.Next)= 0xc0000510f8
&i.Next= 0xc0000510f8 &p.Next= 0xc0000510f8
i.Next= &{0 <nil>} p.Next= &{0 <nil>}
*i= {0 0xc000051110} *j= {0 <nil>} *p= {0 0xc000051110} *q= {0 <nil>}
1----
&i.Next= 0xc000051188
&i= 0xc00000a0b0 &j= 0xc00000a0b8 &p= 0xc00000a0c0 &q= 0xc00000a0c8
&(i.Next)= 0xc000051188 &(p.Next)= 0xc000051188
&i.Next= 0xc000051188 &p.Next= 0xc000051188
i.Next= &{456 <nil>} p.Next= &{456 <nil>}
*i= {0 0xc0000511a0} *j= {123 <nil>} *p= {0 0xc0000511a0} *q= {456 <nil>}
2----
&i.Next= 0xc000051218
2-0---p和i存同一个节点的地址,p的变动会影响i
&i= 0xc00000a0d0 &j= 0xc00000a0d8 &p= 0xc00000a0e0 &q= 0xc00000a0e8
&(i.Next)= 0xc000051218 &(p.Next)= 0xc000051218
&i.Next= 0xc000051218 &p.Next= 0xc000051218
i.Next= &{456 <nil>} p.Next= &{456 <nil>}
*i= {0 0xc000051230} *j= {123 <nil>} *p= {0 0xc000051230} *q= {456 <nil>}
2-1---p和i不存同一个节点的地址,p的变动不会影响i
&i= 0xc00000a0d0 &j= 0xc00000a0d8 &p= 0xc00000a0e0 &q= 0xc00000a0e8
&(i.Next)= 0xc000051218 &(p.Next)= 0xc0000512a8
&i.Next= 0xc000051218 &p.Next= 0xc0000512a8
i.Next= &{456 <nil>} p.Next= <nil>
*i= {0 0xc000051230} *j= {123 <nil>} *p= {0 <nil>} *q= {456 <nil>}
func reverseLinkedList(head *LinkNode) (newHead, newTail *LinkNode) { // 反转单向链表,返回新的头、尾节点 var pre *LinkNode cur := head for cur != nil { next := cur.Next cur.Next = pre // 反转 pre = cur cur = next } head.Next = nil return pre, head } func addr() { var head *LinkNode // 单链表初始化 for i := 10; i > 0; i-- { e := &LinkNode{} e.Val = i e.Next = head head = e } // 内存开辟一个指针地址,存一个新节点的地址 node := head for node != nil { fmt.Println(node.Val) node = node.Next } fmt.Println("head-0", head) head, tail := reverseLinkedList(head) fmt.Println("head-1", head, " tail=", tail) //
node = head for node != nil { fmt.Println(node.Val) node = node.Next } fmt.Println("head-2", head, " tail=", tail) } 1 2 3 4 5 6 7 8 9 10 head-0 &{1 0xc000051140} head-1 &{10 0xc0000510d0} tail= &{1 <nil>} 10 9 8 7 6 5 4 3 2 1 head-2 &{10 0xc0000510d0} tail= &{1 <nil>}