剑指 Offer 24. 反转链表

82 阅读1分钟

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

解题思路

定义三个指针pre、cur、nex,分别指向前一个节点、当前节点、下一个节点,让当前节点指向前一个节点,然后遍历整个链表即可完成反转。

代码

/**
 * 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,cur = head,nex = null;

        while(cur!=null){
            nex = cur.next;
            cur.next = pre;
            pre = cur;
            cur = nex;
        }
        return pre;
    }
}