206 Reverse Linked List
Reverse a singly linked list.
解法: linked list 最典型的题型之一。
public ListNode ReverseList(ListNode head) { var sentinel = new ListNode(0); var dummy = new ListNode(0); dummy.next = head; while(dummy.next != null) { dummy.next = head.next; var temp = sentinel.next; sentinel.next = head; sentinel.next.next = temp; } return sentinel.next; }
思路相同,也可以不用哨兵:
public ListNode ReverseList(ListNode head) { if(head == null) return head; ListNode nextNode = null; ListNode newHead = null; while(head != null) { nextNode = head.next; head.next = newHead; newHead = head; head = nextNode; } return newHead; }