您的位置:首页 > 其它

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

2016-03-03 20:03 483 查看
题目:

Reverse a singly linked list.

Hint:

A linked list can be reversed either iteratively or recursively. Could you implement both?

翻译:

反转一个单链表。

分析:

可以先尝试通过简单例子画图分析,来弄清如何修改指向。

代码:

[code]/**
 * 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;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: