Reverse a singly linked list.
做II之前应该先来做1的,这个导师很简单,基本上不用考虑什么,简单的链表反转而已:
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 == NULL) return NULL; 13 ListNode * prev = NULL; 14 ListNode * p = head; 15 ListNode * next; 16 while(p != NULL){ 17 next = p->next; 18 p->next = prev; 19 prev = p; 20 p = next; 21 } 22 return prev; 23 } 24 };
时间: 2024-11-10 11:55:49