剑指Offer之翻转链表

题目描述:

定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。

思路分析:

  1. 递归法

    该题可以用递归处理。一直递归到最后一个结点,然后翻转最后一个结点,然后翻转倒数第二个结点…返回之前的尾结点,即翻转后的首结点。

    参考代码:

public static ListNode reverseList(ListNode head) {
   if(head == null || head.next == null)return head;
   ListNode root = reverseList(head.next);
   head.next.next = head;
   head.next = null;
   return root;
}
  1. 迭代法:

    设置3个指针pre,curr,next,分别表示前一个结点,当前节点,后一个结点,然后从前到后进行翻转。

    参考代码:

public static ListNode reverseList(ListNode head) {
   if(head == null || head.next == null)return head;
   ListNode pre = null;
   ListNode curr = head;
   ListNode next = head.next;
   while(next != null){
     curr.next = pre;
     pre = curr;
     curr = next;
     next = next.next;
   }
   curr.next = pre;
   return curr;
}

查看更多

(完)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章