题目源自于leetcode。
题目:
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. 不允许交换结点的值。空间复杂度必须是O(1)。
思路: 用三个指针进行交换吧。注意开头和结尾的情况。
代码:
/** * 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) { if (head == NULL) return NULL; ListNode *pp, *pre, *p; pre = head; if(pre->next != NULL) head = pre->next; else return head; pp = new ListNode(0);//这个结点没有意义。只是为了给pp赋一个初值。使得第一次交换的情况和后面的代码保持一致 while(pre != NULL && pre->next != NULL) { p = pre->next; pre->next = p->next; p->next = pre; pp->next = p; pp = pre; pre = pre->next; } return head; } };