206. Reverse Linked List
Reverse a singly linked list.
反转一个链表。
思路:
采用头插法,将原来链表重新插一次返回即可。
代码如下:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { if(NULL == head) return NULL; ListNode *newHead,*p,*q; newHead->next = NULL; p = head; while(p) { q = p; p = p->next; q->next = newHead->next; newHead->next = q; } return newHead->next; } };
2016-08-05 18:59:32