码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode-easy-Reverse Linked List

时间:2016-03-06 11:22:03      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

Reverse a linked list.

For linked list 1->2->3, the reversed linked list is 3->2->1

/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param head: The head of linked list.
     * @return: The new head of reversed linked list.
     */
    public ListNode reverse(ListNode head) {
        // write your code here
        if(head == null || head.next == null)
            return head;
        
        ListNode prev = null;
        ListNode curr = head;
        ListNode next = head.next;
        
        while(next != null){
            curr.next = prev;
            prev = curr;
            curr = next;
            next = next.next;
        }
        curr.next = prev;
        
        return curr;
    }
}

 

lintcode-easy-Reverse Linked List

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5246697.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!