反轉一個單鏈表

原題

  Reverse a singly linked list.算法

題目大意

  反轉單鏈表。spa

解題思路

  使用頭插法。.net

代碼實現

結點類code

public class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

算法實現類get

public class Solution {

    public ListNode reverseList(ListNode head) {
        // 頭結點
        ListNode root = new ListNode(0);
        ListNode nextNode;
        while (head != null) {
            nextNode = head.next;
            head.next = root.next;
            root.next = head;
            head = nextNode;
        }

        return root.next;
    }
}
相關文章
相關標籤/搜索