题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
using System; using System.Collections.Generic; /* public class ListNode { public int val; public ListNode next; public ListNode (int x) { val = x; } } */ class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ public ListNode ReverseList (ListNode head) { // write code here //创建一个栈,保存结点 var stack = new Stack<ListNode>(); //依次将结点压入栈 while (head != null) { stack.Push(head); head = head.next; } //栈为空,返回空 if (stack.Count == 0) return null; //第一个结点 var node = stack.Pop(); //用于返回的链表 var newListNode = node; //依次将栈中的结点,添加到node之后 while (stack.Count > 0) { node.next = stack.Pop(); node = node.next; } //此时node为尾节点,将下一结点需要置空 node.next = null; return newListNode; } }