BM1 反转链表

开始刷数据结构了。
1.递归

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    public ListNode ReverseList (ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode reverseHead = ReverseList(head.next);
        head.next.next = head;
        head.next = null;
        return reverseHead;
    }
}

2.非递归

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    public ListNode ReverseList (ListNode head) {
        ListNode cur = head;
        ListNode next = null;
        ListNode pre = null;
        while(cur != null){
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
}
posted @ 2024-04-12 11:52  YuKiCheng  阅读(5)  评论(0编辑  收藏  举报