81人阅读 评论(0)

Solution 1

Idea: create a dummy node and insert node after dummy node

 * Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:

ListNode* dummy = new ListNode(0);
while(cur->next){
ListNode* tmp = cur->next;
cur->next = tmp->next;
tmp->next = dummy->next;
dummy->next = tmp;
}
return dummy->next;

}
};

Solution 2

Idea: iteratively reverse two nodes

 * Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* pre = NULL;
while (cur&&cur->next){
ListNode* tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
cur->next = pre;
return cur;
}
};

Solution 3

Idea: recursive function

 * Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
return node;
}
};

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：9843次
• 积分：634
• 等级：
• 排名：千里之外
• 原创：31篇
• 转载：150篇
• 译文：0篇
• 评论：0条
文章分类