p206

LeetCode 206 Reverse Linked List 题解

1.题目:

Reverse a singly linked list.

题意:

将一个链表反转

2.解题思路:

见代码

3.代码


[title] [] [url] [link text]
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
 

public class Solution {
public ListNode reverseList(ListNode head) {
if (head==null) return head;
if (head.next==null)
{
ListNode listNode = new ListNode(head.val);
return listNode;
}

ListNode ans =reverseList(head.next);
ListNode n =new ListNode(head.val);
ListNode now=ans;
for (;;)//注意循环到终点再定位next
{

if(now.next==null)
{
now.next=n;
break;
}
now=now.next;
}

return ans;

}
}


4.一些总结: