leetcode-面试题24-反转链表
方法一:迭代
class Solution { public ListNode reverseList(ListNode head) { ListNode pre = null; ListNode cur = head; ListNode tmp = null; while(cur!=null){ tmp = cur.next; cur.next = pre; pre = cur; cur = tmp; } return pre; } }
方法二:递归
class Solution { public ListNode reverseList(ListNode head) { if(head==null || head.next==null){ return head; } ListNode cur = reverseList(head.next); head.next.next = head; head.next = null; return cur; } }
方法三:妖魔化迭代
class Solution { public ListNode reverseList(ListNode head) { if(head==null ){ return null; } ListNode cur = head; while(head.next!=null){ ListNode tmp = head.next.next; head.next.next = cur; cur = head.next; head.next = tmp; } return cur; } }