【剑指Offer】15、反转链表

题目描述

输入一个链表,反转链表后,输出新链表的表头。

题解一:栈
 1 public static ListNode ReverseList(ListNode head) {
 2         if(head==null||head.next==null){
 3             return head;
 4         }
 5         Stack<ListNode> stack = new Stack<>();
 6         ListNode current=head;
 7         while (current!=null){
 8             stack.push(current);
 9             current=current.next;
10         }
11         //关键在于这里,原来的头结点的next要置为空,否则导致遍历时无限循环
12         head.next = null;
13         ListNode backHead=stack.pop();
14         ListNode backCurrent=backHead;
15         while (!stack.isEmpty()){
16             backCurrent.next=stack.pop();
17             backCurrent=backCurrent.next;
18         }
19         return backHead;
20     }
题解二:循环调转方向
 1 //依次遍历所有节点,将所有节点的next指向前一个节点
 2     public static ListNode ReverseList02(ListNode head) {
 3         ListNode pre = null;
 4         ListNode next =null;
 5         while (head != null) {
 6             //持有下一个节点的引用
 7             next = head.next;
 8             //将当前节点对下一个节点的引用指向前一个节点
 9             head.next = pre;
10             //将前一个节点指向当前节点
11             pre = head;
12             //将当前节点指向下一个节点
13             head = next;
14         }
15 //如果head为null的时候,pre就为最后一个节点了,但是链表已经反转完毕,pre就是反转后链表的第一个节点
16         return pre;
17     }
题解三:递归
 1 public static ListNode ReverseList01(ListNode head) {
 2         if(head == null || head.next == null) {
 3             return head;
 4         }
 5         //递归找到尾部节点
 6         ListNode preNode = ReverseList01(head.next);
 7         //倒序
 8         head.next.next = head;
 9         //将正序的头节点指向空
10         head.next = null;
11         return preNode;
12     }

初始化链表:

 1 public static class ListNode{
 2         int val;
 3         ListNode next = null;
 4         ListNode(int val) {
 5             this.val = val;
 6         }
 7     }
 8 public static ListNode createList(int[] list){
 9         ListNode head = new ListNode(-1);
10         ListNode current=head;
11         for(int i=0;i<list.length;i++){
12             current.next=new ListNode(list[i]);
13             current=current.next;
14         }
15         return head.next;
16     }

测试:

 1  public static void main(String[] args) {
 2         int[] list={1,2,3,4,5,6};
 3         ListNode head = createList(list);
 4         ListNode backHead = ReverseList(head);
 5         while (backHead!=null){
 6             System.out.print(backHead.val+" ");
 7             backHead=backHead.next;
 8         }
 9     }
10 输出:6 5 4 3 2 1

猜你喜欢

转载自www.cnblogs.com/Blog-cpc/p/12393117.html
今日推荐