Leetcode206反转链表(视频看了但是题目做不出。。99999)
我的C#代码:(执行超时,肉闷啊:)-_-)
List<ListNode> x_List = new List<ListNode>();
public ListNode ReverseList(ListNode head)
{
if (head == null || head.next == null)
return head;
while (head != null)
{
this.x_List.Add(head);
head = head.next;
}
if (this.x_List.Count <= 0)
return null;
int count = this.x_List.Count;
ListNode listnode = this.x_List[count - 1];
for (int i = count - 1; i > 0; i--)
{
this.x_List[i].next = this.x_List[i - 1];
}
return listnode;
}
别人的代码(整个不理解,知道是颠倒次序,但就是没彻底搞懂; 为什么没有指向next,新的链表竟然成立??)
public ListNode ReverseList(ListNode head)
{
if (head == null)
return null;
ListNode reverse = null;
while (head != null)
{
ListNode tempStore = head.next; // 将 head 的 下一个对象引用临时存储
head.next = reverse;
reverse = head;
head = tempStore;
}
return reverse;
}