/**
* 剑指 Offer 24. 反转链表
* @author wsq
* @date 2020/09/09
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
限制:
0 <= 节点个数 <= 5000
链接:https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof
*/
package notsubmit;
public class ReverseList {
/**
* 采用双指针的方式实现链表的反转
* 也可以尝试通过栈的方式实现,不过需要O(n)的额外空间使用
* @param head
* @return
*/
public ListNode reverseList(ListNode head) {
if(head == null){
return head;
}
ListNode preNode = head;
ListNode lastNode = head.next;
while(lastNode != null) {
ListNode tmpNode = lastNode.next;
lastNode.next = preNode;
preNode = lastNode;
lastNode = tmpNode;
}
head.next = null;
return preNode;
}
/**
* 打印链表
* @param head
*/
public static void printList(ListNode head) {
while(head != null) {
System.out.print(head.val);
if(head.next != null) {
System.out.print("->");
}
head = head.next;
}
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
ListNode node1 = new ListNode(3);
ListNode node2 = new ListNode(2);
head.next = node1;
node1.next = node2;
System.out.println("链表反转前:");
printList(head);
ReverseList rl = new ReverseList();
ListNode ans = rl.reverseList(head);
System.out.println("\n链表反转后:");
printList(ans);
}
}
剑指 Offer 24. 反转链表
最新推荐文章于 2022-02-20 10:35:54 发布