Reverse a singly linked list.算法
反轉單鏈表。spa
使用頭插法。.net
結點類code
public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } }
算法實現類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; } }