剑指offer第二版-24.反转链表

本系列导航:剑指offer(第二版)java实现导航帖

面试题24:反转链表

题目要求:
如题

解题思路:
想要链表反转时不断裂,至少需要3个变量记录,pre,cur,post。与前面的题目类似,初始化pre为null,cur为head,post为head.next。初始化之前要注意检查链表的长度。

package structure;
/**
 * Created by ryder on 2017/6/13.
 */
public class ListNode {
    public T val;
    public ListNode next;
    public ListNode(T val){
        this.val = val;
        this.next = null;
    }
    @Override
    public String toString() {
        StringBuilder ret = new StringBuilder();
        ret.append("[");
        for(ListNode cur = this;;cur=cur.next){
            if(cur==null){
                ret.deleteCharAt(ret.lastIndexOf(" "));
                ret.deleteCharAt(ret.lastIndexOf(","));
                break;
            }
            ret.append(cur.val);
            ret.append(", ");
        }
        ret.append("]");
        return ret.toString();
    }
}
package chapter3;
import structure.ListNode;
/**
 * Created by ryder on 2017/7/14.
 * 反转链表
 */
public class P142_ReverseList {
    public static ListNode reverseList(ListNode head){
        if(head==null || head.next==null)
            return head;
        ListNode pre = null;
        ListNode cur = head;
        ListNode post = head.next;
        while(true){
            cur.next = pre;
            pre = cur;
            cur = post;
            if(post!=null)
                post = post.next;
            else
                return pre;
        }
    }
    public static void main(String[] args){
        ListNode head = new ListNode<>(1);
        head.next= new ListNode<>(2);
        head.next.next = new ListNode<>(3);
        System.out.println(head);
        head = reverseList(head);
        System.out.println(head);
    }
}

运行结果

[1, 2, 3]
[3, 2, 1]

你可能感兴趣的:(剑指offer第二版-24.反转链表)