算法复习:链表
Posted dzzy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法复习:链表相关的知识,希望对你有一定的参考价值。
链表必须清楚掌握
链表定义
struct ListNode { int val; ListNode *next; };
创建链表头
ListNode* creat()//创建头 { struct ListNode *node=(struct ListNode *)malloc(sizeof(struct ListNode)); node->next=NULL; return node; }
创建一个新节点(插入时调用)
ListNode* make_node(int num)//建新节点 { struct ListNode *node=(struct ListNode *)malloc(sizeof(struct ListNode)); node->val=num; node->next=NULL; return node; }
插入新节点(尾插法)
ListNode* insert(ListNode* head,int num)//尾插法 { struct ListNode *str=(struct ListNode *)malloc(sizeof(struct ListNode)); str=head; while(str->next) { str=str->next; } str->next=make_node(num); return head; }
插入新节点(头插法)
ListNode* insert(ListNode* head,int num)//头插法 { struct ListNode *str=make_node(num); str->next=head->next; head->next=str; return head; }
主函数举例(遍历输出,头节点不存数据)
int main() { struct ListNode *head=creat(); insert(head,1); insert(head,1); insert(head,2); insert(head,3); insert(head,4); insert(head,4); insert(head,5); struct ListNode *str=head->next; while(str) { cout<<str->val<<" "; str=str->next; } cout<<endl; return 0; }
使用举例
leedcode 82. 删除排序链表中的重复元素 II
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* deleteDuplicates(ListNode* head) { struct ListNode* pass; struct ListNode* slow; struct ListNode* fast; if(head==NULL||head->next==NULL) return head; //处理头节点要删除的情况 递归删除 int lables=0; while(head!=NULL&&head->next!=NULL&&head->val==head->next->val) { struct ListNode* tmp; tmp=head->next; head->next=tmp->next; delete tmp; lables=1; } if(lables==1) { head=head->next; head=deleteDuplicates(head); } if(head==NULL) return head; pass=head; if(pass==NULL||pass->next==NULL||pass->next->next==NULL) return head; slow=pass->next; fast=slow->next; if(slow->val==fast->val&&fast->next==NULL) { delete slow; delete fast; head->next=NULL; return head; } int lable=0; while(1) { if(fast==NULL&&lable==0) return head; if(fast==NULL&&lable==1) { pass->next=NULL; return head; } if(slow->val!=fast->val&&lable==0)//相邻不等 { pass=slow; slow=fast; fast=fast->next; lable=0; continue; } if(slow->val==fast->val)//slow=fast { struct ListNode* tmp; tmp=fast; fast=fast->next; delete tmp; lable=1; continue; } if(slow->val!=fast->val&&lable==1)//不相邻不相等 { pass->next=fast; slow=fast; fast=fast->next; lable=0; continue; } } return head; } };
以上是关于算法复习:链表的主要内容,如果未能解决你的问题,请参考以下文章
NC41 最长无重复子数组/NC133链表的奇偶重排/NC116把数字翻译成字符串/NC135 股票交易的最大收益/NC126换钱的最少货币数/NC45实现二叉树先序,中序和后序遍历(递归)(代码片段