每天1题算法题(6)- 反转链表(√)
反转一个单链表。
解答
class Solution { public ListNode reverseList(ListNode head) { if(head == null || head.next == null) { return head; } List<ListNode> list = new ArrayList(); while(head != null) { list.add(head); ListNode tmpNode = head.next; head.next = null; head = tmpNode; } ListNode newHead = null; ListNode curHead = null; for(int i = list.size()-1;i>=0;i--) { ListNode tmpNode = list.get(i); if(newHead == null) { newHead = tmpNode; curHead = tmpNode; } else { curHead.next = tmpNode; curHead = tmpNode; } } return newHead; } }