C#LeetCode刷题之#206-反转链表(Reverse Linked List)

原文:https://blog.csdn.net/qq_31116753/article/details/82828513 

问题

反转一个单链表。

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

Reverse a singly linked list.

Input: 1->2->3->4->5->NULL

Output: 5->4->3->2->1->NULL

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode ReverseList(ListNode head) {

        var node=head;
        ListNode pre=null;
        while(node!=null)
        {
            var temp=node.next;

            node.next=pre;
            pre=node;
            node=temp;
        }
        return pre;
    }
}
扫描二维码关注公众号,回复: 4949812 查看本文章

猜你喜欢

转载自blog.csdn.net/qq_35422344/article/details/86491272