1. 程式人生 > >Leetcode 第206題:Reverse Linked List

Leetcode 第206題:Reverse Linked List

連結串列問題

1.遞迴思路

/**
 * 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;
        }

        if
(head.next == null){ return head.next; } ListNode p = head.next; ListNode n = reverseList(p); head.next = null; p.next = head; return n; } }

2.迴圈思路

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution { public ListNode reverseList(ListNode head) { if(head==null || head.next==null){ return head; } ListNode pre = head; ListNode p = head.next; pre.next = null; ListNode nxt; while(p!=null) { nxt = p.next; p.next = pre; pre = p; p = nxt; } return
pre; } }