反转链表
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head){
struct ListNode* pre=NULL;
while(head)
{
struct ListNode* temp=head->next;
head->next=pre;
pre=head;
head=temp;
}
return pre;
}
两两交换链表中的节点
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* swapPairs(struct ListNode* head){
struct ListNode* pre;
struct ListNode* cur;
struct ListNode* temp;
struct ListNode* pHead=(struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* shead=pHead;
pHead->next=head;
pre=cur=head;
//如果将cur->next与pre交换位置,会编译报错
while( pre && cur->next )
{
//cur是需要交换的两个节点的第二个节点,pre是第一个。
cur=cur->next;
//temp是需要交换的两个节点后的第一个节点
temp=cur->next;
//shead是需要交换的两个节点前的一个节点,指向第二个节点
shead->next=cur;
//第二个节点指向第一个节点
cur->next=pre;
//第一个节点指向俩节点后的第一个节点
pre->next=temp;
//第一个节点变成新的需要交换的节点前的节点
shead=pre;
pre=temp;
cur=pre;
}
return pHead->next;
}