leetCode206 - 反轉單鏈表

leetCode206題,反轉單鏈表習題解答

package LinkList;

/**
 * @Auther: DarkKing
 * @Date: 2019/7/22 21:20
 * @Description:
 */
public class LeetCode206 {

    static class Solution {
        public static ListNode reverseList(ListNode head) {
            ListNode cur = head;
            ListNode pre = null;
            ListNode next;
            while (cur != null) {
                //獲取當前節點的下一個節點
                    next = cur.next;
                    //設置當前節點的前置節點
                    cur.next = pre;
                    //將當前節點設置爲前置節點
                    pre = cur;
                    //將下一個節點設置爲當前節點,繼續循環。
                    cur = next;
            }
            return pre;
        }
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public static void main(String[] args) {
        ListNode list= new ListNode(1);
        list.next=new ListNode(2);
        list.next.next=new ListNode(3);
        list.next.next.next=new ListNode(4);
        ListNode list2 = Solution.reverseList(list);
        System.out.println(list2.toString());
    }
}

 

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