思路:一次遍历即可
很简单的题目,唯一需要注意的就是最初把pre设置成null
public class Solution {
public ListNode reverseList(ListNode head) {
if (null == head)
return null;
ListNode pre = null, now = head;
while (null != now) {
ListNode next = now.next;
now.next = pre;
pre = now;
now = next;
}
return pre;
}
}
Go代码
func reverseList(head *ListNode) *ListNode {
if nil == head || nil == head.Next {
return head
}
var pre *ListNode
now := head
for now != nil {
next := now.Next
now.Next = pre
pre = now
now = next
}
return pre
}