leetcode 24. Swap Nodes in Pairs

ゞ 浴缸里的玫瑰 2022-06-09 08:09 234阅读 0赞

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.

这道题考察的是两个节点的交换,这里是指的是指针的交换,而不是值的交换,注意指针即可。

需要注意的地方是:设置head头结点,原因是要对第一队的交换做特殊处理,所以才添加一个head头节点。

代码如下:

  1. /* class ListNode {
  2. int val;
  3. ListNode next;
  4. ListNode(int x) { val = x; }
  5. }*/
  6. /*
  7. * 设置head结点,两两交换
  8. *
  9. * 设置head的原因是:考虑到第一对结点的交换,
  10. * 所以设置head结点,一遍统一处理
  11. *
  12. * */
  13. public class Solution
  14. {
  15. public ListNode swapPairs(ListNode head)
  16. {
  17. if(head==null || head.next==null)
  18. return head;
  19. ListNode headListNode=new ListNode(-1);
  20. headListNode.next=head;
  21. ListNode fa=headListNode,now=fa.next,nextNow=now.next;
  22. while(now!=null && nextNow!=null)
  23. {
  24. now.next=nextNow.next;
  25. nextNow.next=now;
  26. fa.next=nextNow;
  27. fa=now;
  28. now=fa.next;
  29. nextNow=now!=null? now.next : null;
  30. }
  31. return headListNode.next;
  32. }
  33. }

下面是C++代码,就是指针交换即可,

代码如下:

  1. #include <iostream>
  2. using namespace std;
  3. /*
  4. struct ListNode
  5. {
  6. int val;
  7. ListNode *next;
  8. ListNode(int x) : val(x), next(NULL) {}
  9. };
  10. */
  11. class Solution
  12. {
  13. public:
  14. ListNode* swapPairs(ListNode* head)
  15. {
  16. if (head == NULL || head->next == NULL)
  17. return head;
  18. ListNode* newHead = new ListNode(-1);
  19. newHead->next = head;
  20. ListNode* fa = newHead;
  21. ListNode* now = fa->next;
  22. ListNode* next = now->next;
  23. while (now != NULL && next != NULL)
  24. {
  25. ListNode* tmp = next->next;
  26. next->next = now;
  27. fa->next = next;
  28. now->next = tmp;
  29. fa = now;
  30. now = fa->next;
  31. next = now == NULL ? NULL : now->next;
  32. }
  33. return newHead->next;
  34. }
  35. };

发表评论

表情:
评论列表 (有 0 条评论,234人围观)

还没有评论,来说两句吧...

相关阅读