链表---翻转

一、非递归实现

//非递归
private static ListNode reverse(ListNode head) {
             ListNode newHead = null;
             while (head != null) {
                 ListNode temp = head.next;
                 head.next = newHead;
                 newHead = head;
                 head = temp;
             }
             return newHead;
         }


二、递归

public ListNode reverse(ListNode head) {
       if(head==null||head.next==null)return head;

      ListNode temp = reverse(head.next);//head.next表示最后一个节点
      head.next.next = head;//朝前指向(最后一个指向倒数第二个)
      head.next = null;
      return temp;

        
    }

猜你喜欢

转载自blog.csdn.net/l1394049664/article/details/81350270