反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
思路:
迭代方法,链表的题,可以先画图,再考虑去写
<?phpclass ListNode {public $val = 0;public $next = null;function __construct($val) { $this->val = $val; }}class Solution {function reverseList($head){$pre = null;while($head){$tmp = $head->next;$head->next = $pre;$pre = $head;$head = $tmp;}return $pre;}}
func reverseList(head *ListNode) *ListNode {
var prev *ListNode
curr := head
for curr != nil {
next := curr.Next
curr.Next = prev
prev = curr
curr = next
}
return prev
}
时间复杂度:O(n)O(n),其中 nn 是链表的长度。需要遍历链表一次。
空间复杂度:O(1)O(1)。
```
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
