1.找链表倒数第k个节点
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
if(NULL==pListHead||k==0)
return NULL;
ListNode* fast=pListHead;
ListNode* slow=pListHead;
while(k--)
{
if(NULL==fast)
return NULL;
fast=fast->next;
}
while(fast)
{
fast=fast->next;
slow=slow->next;
}
return slow;
}
};
2.单链表的逆置
typedef struct ListNode ListNode;
struct ListNode* reverseList(struct ListNode* head){
ListNode* cur=head;
ListNode* prev=NULL;
ListNode* next=NULL;
while(cur)
{
next=cur->next;
cur->next=prev;
prev=cur;
cur=next;
}
return prev;
}
3.将两个有序链表合并成一个
typedef struct ListNode ListNode;
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
if(NULL==l1)
return l2;
if(NULL==l2)
return l1;
ListNode newHead;
ListNode* cur1=l1;
ListNode* cur2=l2;
ListNode* tailNode=&newHead;
while(cur1&&cur2)
{
if(cur1->val<cur2->val)
{
tailNode->next=cur1;
cur1=cur1->next;
}
else
{
tailNode->next=cur2;
cur2=cur2->next;
}
tailNode=tailNode->next;
}
if(cur1)
tailNode->next=cur1;
else
tailNode->next=cur2;
return newHead.next;
}
4.编写一个程序,找到两个单链表相交的起始节点。
结题要领:
1>确定是否相交:确定最后一个节点是否相同
2>求交点:第一个公共交点
typedef struct ListNode ListNode;
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
if(NULL==headA||NULL==headB)
return NULL;
ListNode* curA=headA;
int countA=1;
while(curA->next)
{
countA++;
curA=curA->next;
}
ListNode* curB=headB;
int countB=1;
while(curB->next)
{
countB++;
curB=curB->next;
}
if(curA!=curB)
return NULL;
curA=headA;
curB=headB;
int gap=countA-countB;
if(gap>0)
while(gap--)
{
curA=curA->next;
}
else{
while(gap++)
{
curB=curB->next;
}
}
while(curA!=curB)
{
curA=curA->next;
curB=curB->next;
}
return curA;
}
5.给定一个链表,判断链表中是否有环。
typedef struct ListNode ListNode;
bool hasCycle(struct ListNode *head) {
ListNode* fast=head;
ListNode* slow=head;
while(fast&&fast->next)
{
fast=fast->next->next;
slow=slow->next;
if(fast==slow)
return true;
}
return false;
}