题目描述
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
题解:非递归
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode tmp = null;
while (head != null) {
tmp = head.next;
head.next = pre;
pre = head;
head = tmp;
}
return pre;
}
}
题解:
题解:递归
class Solution {
ListNode pre = null;
ListNode tmp = null;
public ListNode reverseList(ListNode head) {
if(head == null) return pre;
tmp = head.next;
head.next = pre;
pre = head;
head = tmp;
return reverseList(head);
}
}
文字不太好解释,等我有时间画个图!