LeetCode24、两两交换链表中的节点
struct ListNode * swapPairs ( struct ListNode * head) {
struct ListNode * dummyNode = ( struct ListNode * ) malloc ( sizeof ( struct ListNode ) ) ;
dummyNode-> next = head;
struct ListNode * curr = dummyNode;
while ( curr-> next != NULL && curr-> next-> next!= NULL )
{
struct ListNode * temp = curr-> next;
struct ListNode * temp1 = curr-> next-> next-> next;
curr-> next = curr-> next-> next;
curr-> next-> next = temp;
temp-> next = temp1;
curr = curr-> next-> next;
}
return dummyNode-> next;
}
LeetCode19、删除链表的倒数第N个节点
struct ListNode * removeNthFromEnd ( struct ListNode * head, int n) {
struct ListNode dummy = { 0 , NULL } ;
struct ListNode * dummyNode = & dummy;
dummyNode-> next = head;
n = n + 1 ;
struct ListNode * fast = dummyNode;
struct ListNode * slow = dummyNode;
while ( n-- && fast!= NULL )
{
fast = fast-> next;
}
while ( fast!= NULL )
{
fast = fast-> next;
slow = slow-> next;
}
slow-> next = slow-> next-> next;
return dummyNode-> next;
}
LeetCode02.07、链表相交
struct ListNode * getIntersectionNode ( struct ListNode * headA, struct ListNode * headB) {
struct ListNode * s = NULL ;
struct ListNode * l = NULL ;
int a = 0 ; int b = 0 ; int gap = 0 ;
s = headA;
while ( s)
{
a++ ;
s = s-> next;
}
s = headB;
while ( s)
{
b++ ;
s = s-> next;
}
if ( a > b)
{
gap = a - b;
s = headA;
l = headB;
}
else {
gap = b - a;
s = headB;
l = headA;
}
while ( gap-- )
{
s = s-> next;
}
while ( s)
{
if ( l == s) return s;
l = l-> next;
s = s-> next;
}
return NULL ;
}
LeetCode142、环形链表II
struct ListNode * detectCycle ( struct ListNode * head) {
struct ListNode * fast = head;
struct ListNode * slow = head;
while ( fast!= NULL && fast-> next!= NULL )
{
fast = fast-> next-> next;
slow = slow-> next;
if ( fast == slow)
{
struct ListNode * h = head, * f = fast;
while ( h != f)
{
h= h-> next;
f= f-> next;
}
return h;
}
}
return NULL ;
}