剑指15.反转链表

题目描述

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

思路

为了反转一个链表,需要调整链表中指针的方向。当调整节点 i 的指针指向时,需要知道节点 i 本身,还需要知道 i 的前一个节点 h,因为我们需要把节点 i 的指针指向节点 h 。同时,我们还需要提前保存 i 原来的下一个节点 j ,以防止链表断开。因此,需要3个指针,分别指向当前遍历到的节点,它的前一个节点以及后一个节点。
 

代码实现

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head == null || head.next == null)
            return head;
        ListNode pre = null;
        ListNode current = head;
        ListNode next = null;
        while(current != null){
            next = current.next;
            current.next = pre;
            pre = current;
            current = next;
        }
        return pre;
    }
}
// 第二种写法
public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head == null || head.next == null)
            return head;
        ListNode pre = null;//注意要考虑到第一个节点,让它指向null
        ListNode next = null;
        while(head != null){
            next = head.next; //先记录一下当前节点的下一个节点,以防断开找不到下一个节点
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }
}
 
原文地址:https://www.cnblogs.com/HuangYJ/p/13463106.html