您的位置:首页 > 编程语言 > C#

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

2019-01-15 13:41 525 查看

原文: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?

 

[code]/**
* 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;
}
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: