题目
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
代码
非递归
public ListNode reverseList(ListNode head) { ListNode cur = null, pre = head, temp; while (pre != null) { temp = pre.next; pre.next = cur; cur = pre; pre = temp; } return cur; }
递归
具体可见
public ListNode reverseList(ListNode head) { if (head == null || head.next == null) return head; ListNode ret = reverseList(head.next); head.next.next = head; head.next = null; return ret; }