lintcode刷题记录[java]

简单题35-翻转链表

2018-05-14  本文已影响5人  Airycode

【题目】
描述

翻转一个链表
您在真实的面试中是否遇到过这个题? 是
样例

给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null
挑战

在原地一次翻转完成
【思路】
两个头指针 一个cur 找下一个 然后赋予到reverse上
【代码实现】

/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param head: n
     * @return: The new head of reversed linked list.
     */
    public ListNode reverse(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode cur = head;
        ListNode reverse = null;
        while (cur != null) {
            ListNode temp = cur.next;
            cur.next = reverse;
            reverse = cur;
            cur=temp;
        }
        return reverse;
    }
}
上一篇下一篇

猜你喜欢

热点阅读