劍指offer:單鏈表的逆轉

輸入一個鏈表,反轉鏈表後,輸出新鏈表的表頭。
思路一:迭代

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
import java.util.*;
public class Solution {
    public ListNode ReverseList(ListNode head) {
    Listnode cur=null,pre=head;
    while(pre!=null){
    Listnode t=pre.next;
    pre.next=cur;
    cur=pre;
    pre=t;
    }
    return pre;
}
}

思路二:遞歸


```java
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;
    }
}

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