Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
我的做法:
我不会链表at all,so to save time,直接看的答案。
solution:
先说iteratively的做法:
next_node = cur_node.next
cur_node.next = prev_node
prev_node = cur_node
cur_node = next_node
这四句话非常有用,一定要背下来,就是基本的reverse的操作方法,就跟换temp一样基本。。。
至于recursively的方法:
if (head == null || head.next == null) return head; ListNode p = reverseList(head.next); head.next.next = head; head.next = null; return p;其实道理和迭代是一样的。。
链表这玩意儿还是比较抽象,要深刻领会才行。。。