Leet Code OJ 206. Reverse Linked List [Difficulty: Easy]

题目:
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;
    }
}

你可能感兴趣的:(LeetCode,算法,单链表)