Description

难度简单:剑指 Offer 24. 反转链表
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
限制:
0 <= 节点个数 <= 5000

Solution

如图所示,不断变化 head 的 next 节点的指向,依次将链表反转
剑指Offer 24. 反转链表 - 图1
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null)
return head;
ListNode pre = head;
ListNode cur = head;
while(head.next != null){
cur = head.next;
head.next = cur.next;
cur.next = pre;
pre = cur;
}
return cur;
}
}

Solution 2

剑指Offer 24. 反转链表 - 图2
public class Solution{
public ListNode reverseList(ListNode head){
if( head == null)
return head;
ListNode pre = null, next = null;
while( head.next != null){
next = head.next;
head.next = pre;
pre = head;
head = next;
}
head.next = pre;
return head;
}
}