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.
思路:
定义三个指针分别为p, q, k,先让q指针指向p节点,将两个链表节点交换,p指针指向k节点,如果链表的下一个节点不为空时将三个指针整体后移直到结束
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* swapPairs(struct ListNode* head) {
if(head == NULL || head->next == NULL) return head;
struct ListNode *p = head, *q = head->next, *k = head->next->next;
head = head->next;
while(1) {
q->next = p;
p->next = k;
//判断k和k的后边是否为空
if(k && k->next) {
//整体后移
p->next = k->next;
}
p = k;
if(p == NULL ||p->next == NULL) break;
q = p->next;
k = q->next;
}
return head;
}