leetcode——链表——206——链表反转

leetcode 链表专题206——链表反转

示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题

思路:使用迭代法

public class Solution206 {
	// 递归一
	public ListNode reverseList1(ListNode head) {
		ListNode newHead = head, node = head;
		if (node.next == null)
			return node;
		ListNode next = node.next;
		newHead = reverseList1(next);
		next.next = node;
		node.next = null;
		return newHead;
	}
	
	// 递归二(代码上的优化)
	public ListNode reverseList2(ListNode head) {
		if (head == null || head.next == null)
			return head;
		ListNode node = head.next;
		ListNode newHead = reverseList2(node);
		node.next = head;
		head.next = null;
		return newHead;
	}
	
	public void printList(ListNode head) {
		ListNode node = head;
		while(node != null) {
			System.out.println(node.val);
			node = node.next;
		}
	}

	public static void main(String[] args) {
		ListNode node1 = new ListNode(5);
		ListNode node2 = new ListNode(7);
		ListNode node3 = new ListNode(4);
		node1.next = node2;
		node2.next = node3;
		Solution206 test = new Solution206();
		test.printList(node1);
		ListNode newHead = test.reverseList2(node1);
		test.printList(newHead);
	}

}

 

你可能感兴趣的:(LeetCode)