/**
* 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||head->next==NULL)//如果只有一个点,直接返回首结点;
return head;
ListNode*L = head;
ListNode*p = NULL, *q = NULL, *s = NULL;
ListNode*pre = new ListNode(0);//为了方便设置一个头结点;
pre->next = head;
ListNode*flag = pre;
int count = 0,num;
while (L != NULL)//求出链表的长度;
{
count++;
L = L->next;
}
for (int i = 0; i < (count / 2); i++)
{
p = flag->next;
q = p->next;
s = q->next;
q->next = p;
flag->next = q;
p ->next= s;
flag = p;//链接后面的部分;
}
return pre->next;
}
};
24. Swap Nodes in Pairs
最新推荐文章于 2024-09-12 19:02:20 发布