/**
* 面试题24:反转链表.leetcode HOT100第206题
* 输入一个链表,反转链表后,输出新链表的表头。
* 输入{1,2,3},输出{3,2,1}
* @author dengjie
* @create 2021-03-23 12:32
*/
public class Solution24 {
public static void main(String[] args) {
Node node1 = new Node(1);
Node node2 = new Node(2);
Node node3 = new Node(3);
Node node4 = new Node(4);
Node node5 = new Node(5);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
Node res = reverseListThree(node1);
System.out.println(res);
}
/**
* 方法一:迭代,剑指Offer,头插法
* @param head
* @return
*/
public static Node reverseList(Node head){
if (head == null || head.next == null){
return head;
}
Node newHead = new Node(0);//链表反转后的头节点
Node temp = null;//记录当前节点的下一个节点
Node pHead = head;//指向当前节点
while (pHead != null){
temp = pHead.next;
pHead.next = newHead.next;
newHead.next = pHead;
pHead = temp;
}
return newHead.next;
}
/**
* leetcode206简单题,迭代
* @return
*/
public static Node reverseListTwo(Node head){
if(head == null || head.next == null){
return head;
}
Node pre = null;
Node cur = head;
while (cur != null){
Node temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
/**
* 方法三:递归
* @param head
* @return
*/
public static Node reverseListThree(Node head){
if (head == null || head.next == null) {
return head;
}
// 想象递归已经层层返回,到了最后一步
// 以链表 1->2->3->4->5 为例,现在链表变成了 5->4->3->2->null,1->2->null(是一个链表,不是两个链表)
// 此时 newHead是5,head是1
Node newHead = reverseList(head.next);
// 最后的操作是把链表 1->2->null 变成 2->1->null
// head是1,head.next是2,head.next.next = head 就是2指向1,此时链表为 2->1->2
head.next.next = head;
// 防止链表循环,1指向null,此时链表为 2->1->null,整个链表为 5->4->3->2->1->null
head.next = null;
return newHead;
}
}
【剑指Offer】面试题24:反转链表
最新推荐文章于 2022-05-05 10:42:52 发布