leetcode206

时间:2022-02-10 00:37:41
/**
* 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 > )
{
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

简化的代码:

 public class Solution
{
public ListNode ReverseList(ListNode head)
{
//ListNode p = head;
ListNode n = null;
while (head != null)
{
ListNode temp = head.next;
head.next = n;
n = head;
head = temp;
}
return n;
}
}

补充一个python的实现:

 class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
temp = ListNode()
while head != None:
nextnode = head.next
head.next = temp.next
temp.next = head
head = nextnode
return temp.next