题目

反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

解析

模板题,注意head为空的情况

代码

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode(int x) : val(x), next(NULL) {}
  7. * };
  8. */
  9. class Solution {
  10. public:
  11. ListNode* reverseList(ListNode* head) {
  12. if (!head) return NULL;
  13. ListNode* dummy = new ListNode(-1);
  14. dummy->next = head;
  15. ListNode* pre = dummy;
  16. ListNode* cur = dummy->next;
  17. while (cur->next) {
  18. ListNode* nxt = cur->next;
  19. cur->next = nxt->next;
  20. nxt->next = pre->next;
  21. pre->next = nxt;
  22. }
  23. return dummy->next;
  24. }
  25. };