题目源自于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;
}
};

本文介绍了一个LeetCode上的经典题目——两两交换链表中的节点的解决方案。该算法通过三个指针操作,在常数空间内完成相邻节点的交换,不改变节点值仅调整节点连接顺序。
1001

被折叠的 条评论
为什么被折叠?



