剑指offer刷题记录15——反转链表

题目描述

输入一个链表,反转链表后,输出新链表的表头。

很典型的一道题,使用三个指针,第一个存分离出来的新链表,第二个存即将进入新链表的表头,第三个存第二个指针的下一个结点,防止第二个结点进入新链表后丢失其子结点。

解法一:

public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head == null) {
            return null;
        }
        if(head.next == null) {
            return head;
        }
        ListNode p1 = head.next;
        ListNode p2 = p1.next;
        head.next = null;
        while(p1.next != null) {
            p1.next = head;
            head = p1;
            p1 = p2;
            p2 = p2.next;
        }
        p1.next = head;
        return p1;
    }
}

运行时间:17ms

占用内存:9424k

猜你喜欢

转载自blog.csdn.net/qq_37684824/article/details/82913454
今日推荐