题目
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
解决方案
递归的实现
public class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode head_node = reverseList(head.next);
head.next.next = head;
head.next = null;
return head_node;
}
}
迭代的实现
class Solution {
public ListNode reverseList(ListNode head) {
ListNode curr = head;
ListNode prev = null;
ListNode next = null;
ListNode head_node = head;
while(curr!=null){
next = curr.next;
if(next==null){
//下个节点为null,标识已经转换最后一个节点了
head_node = curr;
}
curr.next = prev;
prev = curr;
curr = next;
}
return head_node;
}
}