循环链表
第一题
struct Node* insert(struct Node* head, int insertVal) {
struct Node*new=malloc(sizeof(struct Node));
new->next=new;
new->val=insertVal;
if(head==NULL)
{
head=new;
head->next=new;
return head;
}
struct Node*tmp=head;
do
{
if(tmp->val > tmp->next->val&&(insertVal >= tmp->val || insertVal<=tmp->next->val))
{
new->next=tmp->next;
tmp->next=new;
return head;
}
else if(tmp->next->val >= insertVal && insertVal>=tmp->val)
{
new->next=tmp->next;
tmp->next=new;
return head;
}
else if(tmp->next==head)
{
new->next=tmp->next;
tmp->next=new;
return head;
}
tmp=tmp->next;
}while(tmp!=head);
return head;
}
循环条件cur!=head(所给的随意结点)
环形链表
第一题
struct ListNode *detectCycle(struct ListNode *head) {
struct ListNode*fast,*slow;
struct ListNode*ptr;
fast=slow=ptr=head;
while(fast&&fast->next)
{
if(fast&&fast->next)
{
fast=fast->next->next;
}
if(slow->next)
{
slow=slow->next;
}
if(fast==slow)//相遇说明一定有环
{
while(ptr!=slow)
{
ptr=ptr->next;
slow=slow->next;
}
return slow;
}
}
return NULL;
}
总结:环形链表或是找倒数第k个结点,可以用快慢指针,快的一次2步,慢的一次1步,考虑快慢如果相遇或者快指针到末尾时的情况,考虑快慢指针的步长差等条件
第二题
struct ListNode* reverseList(struct ListNode* head){
struct ListNode* front = NULL;
struct ListNode* mid = head;
while(mid != NULL)
{
struct ListNode* end = mid->next;
mid->next = front;
front = mid;
mid = end;
}
return front;
}
int pairSum(struct ListNode* head){
int ans=0;
int temp;
struct ListNode*slow=head;
struct ListNode*fast=head->next;//视题目而定
while(fast->next)//因为是偶数
{
fast=fast->next->next;
slow=slow->next;
}//slow到达中间结点
struct ListNode*last=slow->next;
struct ListNode*x=head;
struct ListNode*y=reverseList(last);
while(y)
{
temp=x->val+y->val;
ans=ans>temp?ans:temp;
x=x->next;
y=y->next;
}
return ans;
}
思路:运用快慢指针拿到中间结点,将中间之后的结点翻转,顺序遍历