首页 > 其他 > 详细

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

时间:2016-03-03 21:24:55      阅读:237      评论:0      收藏:0      [点我收藏+]

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

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

原文:http://blog.csdn.net/lnho2015/article/details/50791239

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!