0%

leetCode-206:Reverse Linked List

问题描述

给定一个链表,要求将其反转。题目链接:**点我**

样例输入输出

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

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

输入:1

输出:1

问题解法

此题很明确,也没什么算法,直接反转即可。代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution
{
public ListNode reverseList(ListNode head)
{
if (head == null)
{
return head;
}

ListNode dummy = new ListNode(-1, head);
while (head.next != null)
{
ListNode p = dummy.next;
dummy.next = head.next;
head.next = head.next.next;
dummy.next.next = p;
}

return dummy.next;
}
}