招修仙系列 —— leetcode 206反转链表

题目:
反转一个单链表。

示例 1:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

代码1:

/** 循环法 **/
class Solution {
    public ListNode reverseList(ListNode head) {
      if(head == null || head.next == null) return head;
      ListNode cur = head,next = null,pre = null;
      while(cur != null){
        next = cur.next;
        cur.next = pre;
        pre = cur;
        cur = next;
      }
      return pre;       
    }
}

结果1:

在这里插入图片描述

代码2:

/** 递归法 **/
class Solution {
    public ListNode reverseList(ListNode head) {
      if(head == null || head.next == null){
        return head;
      }
      ListNode node = reverseList(head.next);
      head.next.next = head;
      head.next = null;
      return node;       
    }
}

结果2:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Kirito19970409/article/details/86567410