反转链表
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;
}
两两交换链表中的节点
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;
while( pre && cur->next )
{
cur=cur->next;
temp=cur->next;
shead->next=cur;
cur->next=pre;
pre->next=temp;
shead=pre;
pre=temp;
cur=pre;
}
return pHead->next;
}
删除链表的倒数第N个节点
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
struct ListNode* sHead;
sHead=(struct ListNode*)malloc(sizeof(struct ListNode));
sHead->val=0;
sHead->next=head;
struct ListNode* slow=sHead;
struct ListNode* fast=head;
int i=n;
while( fast )
{
if(n)
{
fast=fast->next;
n--;
}
else
{
fast=fast->next;
slow=slow->next;
}
}
slow->next=slow->next->next;
return sHead->next;
}
链表相交
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
if(headA==NULL || headB==NULL ) return NULL;
int lenA=0,lenB=0;
int gap;
struct ListNode* s;
struct ListNode* l;
s=headA;
while(s)
{
s=s->next;
lenA++;
}
s=headB;
while(s)
{
s=s->next;
lenB++;
}
if(lenA>lenB)
{
gap=lenA-lenB;
l=headA;
s=headB;
}
else
{
gap=lenB-lenA;
l=headB;
s=headA;
}
while(gap--) l=l->next;
while(l)
{
if(l==s) return s;
l=l->next;
s=s->next;
}
return NULL;
}
环形链表II
struct ListNode *detectCycle(struct ListNode *head) {
struct ListNode* fast = head;
struct ListNode* slow = head;
while( fast && fast->next )
{
slow = slow->next;
fast = fast->next->next;
if( slow==fast )
{
struct ListNode* index1 = head;
struct ListNode* index2 = fast;
while( index1 != index2 )
{
index1 = index1->next;
index2 = index2->next;
}
return index1;
}
}
return NULL;
}