题目:
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
进阶:
迭代或递归实现反转链表。
解题:
递归实现反转链表
//递归实现
class Solution {
public ListNode reverseList(ListNode head) {
if(head ==null || head.next == null){
return head;
}
ListNode pre = reverseList(head.next);
head.next.next = head;
head.next = null;
return pre;
}
}
迭代实现反转链表
//迭代实现
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode pre = null;
while( head != null){
ListNode temp = head.next;
head.next = pre;
pre = head;
head = temp;
}
return pre;
}
}