题目描述
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
提交结果:
三指针法(循环)
核心思想:
设立三个指针 ,依次完成反转,在反转之前需要存储下一个结点的地址,否则后面的结点会丢失。
- cur 指针 : 待反转的结点,cur初始化为head。
- next指针 : 后继节点即next = cur.next.
- prev 指针:前驱结点,初始化为null,因为头节点的next指针最终指向null。
具体操作:
从头开始遍历链表,让cur.next指向prev,在此之前next指针先保存cur的next,防止结点丢失,然后逐步向后遍历,直至cur == null,此时链表反转完毕,prev则是新的链表头。
代码实现:
public class ReverseList {
public ListNode Reverse(ListNode head){
// 空链表和一个结点的链表都无需反转
if(head == null || head.next == null){
return head;
}
ListNode prev = null;
ListNode cur = head;
while(cur != null){
ListNode next= cur.next;
cur.next = prev;
prev =cur;
cur = next;
}
return prev;
}
}
递归解法
待反转链表:
对子链表进行递归:即newList= reverseR(head.next);递归后的结果如下:
此时第一个结点和第二个结点间还没有链接好,让2结点的next指向1,1的next指向null就ok了。
代码实现:
public class ReveseR {
public static ListNode reverseR(ListNode head){
//空链表和一个结点的链表无需反转
if(head == null || head.next == null){
return head;
}
ListNode res = reverseR(head.next);
//第二个结点的next指向第一个结点
head.next.next = head;
//第一个结点的next指向null
head.next = null;
return res;
}
}