leetcode24

leetcode 24:

Given a linked list, swap every two adjacent nodes and return its head.

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3

Note:

  • Your algorithm should use only constant extra space.
  • You may not modify the values in the list's nodes, only nodes itself may be changed.
  • 解决这道题的思路是,就是构造一个伪的头结点,然后画出示意图,这样就让指针能够指出正确的位置。:)另外在做此题的时候不要忘记一些特殊情况。下面就是我贴出来的代码。
  • /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* swapPairs(ListNode* head) {
            ListNode* fakehead = (ListNode*)malloc(sizeof(ListNode)); //构建伪头节点
            fakehead->next = head;
            ListNode *p1,*p2;
            p1 = head;
            if(head ==NULL)
            {
                return fakehead->next;
            }
            p2 = p1->next;
            if(p2==NULL)
            {
                return fakehead->next;
            }
            fakehead->next = p2;
            ListNode * tmp; //用来保存上一次的p1节点。
            while(p2!=NULL)
            {
              p1->next = p2->next;
              p2->next = p1;
              tmp= p1;
              p1 = p1->next;
              if(p1!=NULL)
              {
                   p2 = p1->next;
                   tmp->next = p2;
              } 
              else
              {
                 break;
              }
               
            }
            tmp->next = p1;
            return fakehead->next;//返回真正的头结点。
        }
    };

    结语:哈哈哈,一天至少一道题,脑袋不笨:)

猜你喜欢

转载自blog.csdn.net/miracle22222/article/details/85041043