题目描述
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
思路
1.使用递归的思想求解。
2.具体执行过程,请见下图。
![](https://img.haomeiwen.com/i13555794/55e5490b9e5f8f61.png)
Java代码实现
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode res = reverseList(head.next);
head.next.next = head;
head.next = null;
return res;
}
Golang代码实现
func reverseList(head *ListNode) *ListNode {
if head == nil || head.Next == nil{
return head
}
p := reverseList(head.Next)
head.Next.Next = head
head.Next = nil
return p
}
网友评论