首页 > 学院 > 开发设计 > 正文

24. Swap Nodes in Pairs

2019-11-08 01:02:43
字体:
来源:转载
供稿:网友
Given a linked list, swap every two adjacent nodes and return its head.For example,Given 1->2->3->4, you should return the list as 2->1->4->3.Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

解法一:递归

public: ListNode* swapPairs(ListNode* head) { if(head == NULL || head->next == NULL) return head; ListNode* new_head = head->next; head->next = swapPairs(new_head->next); new_head->next = head; return new_head; }};

解法二:非递归

class Solution {public: ListNode* swapPairs(ListNode* head) { ListNode* new_head = NULL; ListNode** pp = &new_head; while(head != NULL){ if(head->next == NULL){ *pp = head; break; } else{ *pp = head->next; head->next = (*pp)->next; (*pp)->next = head; pp = &(head->next); head = head->next; } } return new_head; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表