反转链表

2019-10-16  本文已影响0人  Haward_

题目:
反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list

(1)递归

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    ListNode res = null;
    public ListNode reverseList(ListNode head) {
        if(head==null) {
            return null;
        }
        ListNode q = head.next;
        ListNode p = head;
        p.next = null;
        fReverseList(q,p);
        return res;
    }
    
    private void fReverseList(ListNode head, ListNode pre) {
        if(head==null) {
            res = pre;
            return;
        }
        ListNode p = head.next;
        head.next = pre;
        fReverseList(p,head);
    }
}

(2)非递归

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null) {
            return null;
        }
        ListNode pi = head;
        ListNode pj = pi.next;
        if(pj==null) {
            return pi;
        }
        ListNode pk = pj.next;
        if(pk==null) {
            pi.next = null;
            pj.next = pi;
            return pj;
        }
        pi.next = null;
        while(pk!=null) {
            pj.next = pi;
            pi = pj;
            pj = pk;
            pk = pk.next;
        }
        pj.next = pi;
        return pj;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读