1、翻转链表
void reverseNodes(ListNode *start, ListNode *end) { //翻转链表 ListNode *second = start -> next; ListNode *first = start; ListNode *temp; while(second != end) { temp = second -> next; second -> next = first; first = second; second = temp; } second -> next = first; } //翻转后start指向最后一个节点
2、链表相邻的k个节点翻转
void reverseNodes(ListNode *start, ListNode *end) { ListNode *second = start -> next; ListNode *first = start; ListNode *temp; while(second != end) { temp = second -> next; second -> next = first; first = second; second = temp; } second -> next = first; } ListNode *reverseKGroup(ListNode *head, int k) { ListNode *tempHead = head, *tempEnd = head; ListNode *result = head; ListNode *preEnd = head; ListNode *temp = NULL; bool flag = true; int count = 1; if(!head) { return NULL; } while(tempEnd -> next) { tempEnd = tempEnd -> next; count++; if(count == k) { temp = tempEnd -> next; if(flag) { flag = false; result = tempEnd; reverseNodes(tempHead, tempEnd); tempHead -> next = temp; count = 1; } //翻转第一个k个节点; else { preEnd -> next = tempEnd; preEnd = tempHead; reverseNodes(tempHead, tempEnd); tempHead -> next = temp; count = 1; }//翻转后面的节点 if(temp) { tempHead = temp; tempEnd = temp; } else { tempHead -> next = NULL; return result; } } } return result; } };
//以上程序是有问题的,不知道哪里错了,下面是个accepted
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseKGroup(ListNode* head, int k) { ListNode** re=&head; ListNode* pre=head; ListNode* q=NULL; while(true) { int i=k; ListNode* temp=pre; while(temp!=NULL&&--i>0) { temp=temp->next; } //取到K个节点的尾 if(temp==NULL) return head;//如果没有K长度,返回 i=k; while(i--) { //翻转 ListNode *p_next=pre->next; pre->next=q; q=pre; pre=p_next; } (*re)->next=pre; ListNode *t=*re; *re=q; re=&(t->next); q=NULL; } return head; } };
时间: 2024-10-08 06:13:42