剑指offer之反转链表(Java实现)

反转链表

NowCoder

题目描述:

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

解题思路:

/*
public class ListNode {
    int val;
    ListNode next = null;
 
    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        ListNode pre = null;
        ListNode next = null;
        if(head == null){
            return null;
        }
        while(head != null){
            //记录当前结点的下一个结点,以放丢失
            next = head.next;
            //两两进行交换
            head.next = pre;
            pre = head;
            //后移一位
            head = next;
        }
        return pre;
    }
}

你可能感兴趣的:(剑指offer)