206.反转单链表 Reverse Linked List

Reverse a singly linked list.

public class Solution {
    public ListNode ReverseList(ListNode head) {
		if (head == null) {
			return null;
		}
		Stack<int> stack = new Stack<int>();
		stack.Push(head.val);
		var node = head.next;
		while (node != null) {
			stack.Push(node.val);
			node = node.next;
		}
		head.val = stack.Pop();
		node = head.next;
		while (node != null) {
			node.val = stack.Pop();
			node = node.next;
		}
		return head;
    }
}

  

递归实现

public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head==null || head.next==null)
            return head;
        ListNode nextNode=head.next;
        ListNode newHead=ReverseList(nextNode);
        nextNode.next=head;
        head.next=null;
        return newHead;
    }
}

  

原文地址:https://www.cnblogs.com/xiejunzhao/p/6271235.html