Reverse a singly linked list.

使用栈
  1. public class Solution {
  2. public ListNode ReverseList(ListNode head) {
  3. if (head == null) {
  4. return null;
  5. }
  6. Stack<int> stack = new Stack<int>();
  7. stack.Push(head.val);
  8. var node = head.next;
  9. while (node != null) {
  10. stack.Push(node.val);
  11. node = node.next;
  12. }
  13. head.val = stack.Pop();
  14. node = head.next;
  15. while (node != null) {
  16. node.val = stack.Pop();
  17. node = node.next;
  18. }
  19. return head;
  20. }
  21. }


递归版本
  1. public class Solution {
  2. public ListNode ReverseList(ListNode head) {
  3. if(head==null || head.next==null)
  4. return head;
  5. ListNode nextNode=head.next;
  6. ListNode newHead=ReverseList(nextNode);
  7. nextNode.next=head;
  8. head.next=null;
  9. return newHead;
  10. }
  11. }


05-11 16:16
查看更多