/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int x) { val = x; } * } */ public class Solution { Stack<ListNode> S = new Stack<ListNode>(); private void SaveList(ListNode node) { if (node != null) { S.Push(node); if (node.next != null) { SaveList(node.next); } } } private ListNode GetLastNode(ListNode head) { while (head.next != null) { head = head.next; } return head; } public ListNode ReverseList(ListNode head) { SaveList(head); ListNode newhead = null; while (S.Count > 0) { var curnode = S.Pop(); curnode.next = null; if (newhead == null) { newhead = curnode;//找到链头 } else { var prenode = GetLastNode(newhead);//找到新的链尾 prenode.next = curnode; } } return newhead; } }
https://leetcode.com/problems/reverse-linked-list/#/description
简化的代码:
1 public class Solution 2 { 3 public ListNode ReverseList(ListNode head) 4 { 5 //ListNode p = head; 6 ListNode n = null; 7 while (head != null) 8 { 9 ListNode temp = head.next; 10 head.next = n; 11 n = head; 12 head = temp; 13 } 14 return n; 15 } 16 }
补充一个python的实现:
1 class Solution(object): 2 def reverseList(self, head): 3 """ 4 :type head: ListNode 5 :rtype: ListNode 6 """ 7 temp = ListNode(0) 8 while head != None: 9 nextnode = head.next 10 head.next = temp.next 11 temp.next = head 12 head = nextnode 13 return temp.next