原题链接:https://leetcode-cn.com/problems/reverse-linked-list/
执行用时: 156 ms, 在Reverse Linked List的C#提交中击败了55.73% 的用户
c#解题:
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode header = new ListNode(-1);
ListNode prev = null;
ListNode cur = head;
while (cur!=null)
{
ListNode next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
c#递归:
执行用时: 156 ms, 在Reverse Linked List的C#提交中击败了55.73% 的用户
public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null || head.next == null)
{
return head;
}
ListNode newHead = ReverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}