Day1 AcWing 35. 反转链表
Day1 LeetCode 92. 反转链表 II
思路
- 链表
代码
35. 反转链表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
class Solution { public: ListNode* reverseList(ListNode* head) { if(!head||!head->next) return head; auto a=head,b=a->next; while(b) { auto c=b->next; b->next=a; a=b,b=c; } head->next=NULL; return a; } };
|
92. 反转链表 II
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
class Solution { public: ListNode* reverseBetween(ListNode* head, int m, int n) { if (m == n) return head; ListNode *dummy = new ListNode(0); dummy->next = head; ListNode *p = dummy; for (int i = 0; i < m - 1; i ++ ) p = p->next; ListNode *a = p, *b = a->next, *c = b->next; for (int i = m + 1; i <= n; i ++ ) { ListNode *d = c->next; c->next = b; b = c; c = d; } a->next->next = c; a->next = b; return dummy->next; } };
|