题目:
Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
翻译:
反转一个单链表。
分析:
可以先尝试通过简单例子画图分析,来弄清如何修改指向。
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
if(head==null){
return null;
}
ListNode nextNode=null;
ListNode currentNode=head;
ListNode lastNode=null;
while(true){
nextNode=currentNode.next;
currentNode.next=lastNode;
if(nextNode==null){
break;
}
lastNode=currentNode;
currentNode=nextNode;
}
return currentNode;
}
}