迭代方法
/**
* 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) {
ListNode* pre=nullptr;
ListNode* cur=head;
while(cur){
ListNode* temp=cur->next;
cur->next=pre;
pre=cur;
cur=temp;
}
return pre;
}
};
递归方法
/**
* 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) {
return reverse(NULL,head);
}
private:
ListNode* reverse(ListNode* pre,ListNode* cur){
if(cur==NULL) return pre;
ListNode* next = cur->next;
cur->next = pre;
return reverse(cur,next);
}
};
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head==nullptr||head->next==nullptr){
return head;
}
ListNode* newhead=head->next;
head->next=swapPairs(newhead->next);
newhead->next=head;
return newhead;
}
};
https://leetcode-cn.com/problems/reverse-nodes-in-k-group/
递归方法(java)
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode pre = head;
ListNode cur = head.next;
int n = k;
int countk = 1;
while(n>1){
if(cur == null && countk < k)//判断子链表不足k
return reverseKGroup(pre,countk);//再翻转
ListNode temp = cur.next;
cur.next = pre;
head.next = temp;
pre = cur;
cur = temp;
n--;
countk++;
}
if(cur != null && cur.next != null)
head.next = reverseKGroup(cur,k);//递归链接子链表
return pre;
}
}
这题用了两小时Orz……太菜了