剑指Offer-24 翻转链表

102 阅读1分钟

题意

定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

示例

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

解答

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        // 定义三个链表用于交换与临时存储
	// 分别对应 前指针位置 / 当前指针 / 后指针位置
	ListNode pre = null;
        ListNode current = head;
        ListNode next = null;
	
	// 当前指针不为空的时候
        while(current != null){
            // 暂存后面指针 假如当前节点是 A->B
            next = current.next;
	    // 交换前后指针的值 
	    // 原本 current -> next ,临时pre = null
	    // 交换后 next -> current -> pre(null)
            current.next = pre;
            pre = current;
	    // 继续交换下一个指针
            current = next;
        }
        return pre;
    }
}