题解 | #反转链表#
反转链表
http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
思路
- 遍历遍历链表的节点 for
- 当前节点指向上一个节点 pHead.Next=pre
- 上一个节点变成当前节点 pre=Phead
- 下一个节点变成当前节点 pHead=next
- 当前节点如果是nil停止遍历 pHead!=nil
- 返回当前节点 pre
代码
package main
import . "nc_tools"
/*
* type ListNode struct{
* Val int
* Next *ListNode
* }
*/
/**
*
* @param pHead ListNode类
* @return ListNode类
*/
func ReverseList( pHead *ListNode ) *ListNode {
var pre,next *ListNode
for pHead !=nil{
next=pHead.Next
pHead.Next=pre
pre=pHead
pHead=next
}
return pre
}
查看3道真题和解析