这篇文章用来总结有通用性的代码参考,以后会不定时更新
链表的定义
typedef struct myNode inode;
struct myNode{
inode* next;
int data;
};
生成链表
注意一点:为了操作方便,设置了一个空的头结点
/************************************
生成一个链表,并且返回头结点
(数组的大小不能小于n,否则会越界)
*************************************/
inode* list_init(int a[], int n){
inode*head = new inode();
inode*current = head;
for (int i = 0; i < n; i++){
inode* nn = new inode();
nn->data = a[i];
current->next = nn;
current = nn;
}
return head;
}
删除链表中的重复元素
/*基本思想是用一个map来记录之前遍历过的链表元素,如果当前元素存在于其中,则删除之*/
#include<map>
void removeDuplicate(inode* head){
if (head == NULL)
return;
map<int, bool> mapcount;
inode* p = head;
inode* q = head->next;
/*遍历对象是q,p是为了保留其前一个结点*/
while (q != NULL){
if (mapcount[q->data]){
inode* temp = q;
p->next = q->next;
q = q->next;
delete temp;
}
else{
mapcount[q->data] = true;
p = q;
q = q->next;
}
}
}
两个链表的相加
你有两个由单链表表示的数。每个结点代表其中的一位数字。数字的存储是逆序的, 也就是说个位位于链表的表头。写一函数使这两个数相加并返回结果,结果也由链表表示。
inode* add_list(inode* left_head, inode* right_head){
inode* p = left_head->next;
inode* q = right_head->next;
int c = 0;
inode* res_head = new inode();
inode* current = res_head;
while (p && q){
inode* nn = new inode();
int t = p->data + q->data + c;
nn->data =t%10;
c = t/ 10;
current->next = nn;
current = nn;
p = p->next;
q = q->next;
}
while (q){
inode* nn = new inode();
int t = q->data + c;
nn->data = t%10;
c = t / 10;
current->next = nn;
current = nn;
q = q->next;
}
while (p){
inode* nn = new inode();
int t = p->data + c;
nn->data =t%10;
c = t / 10;
current->next = nn;
current = nn;
p=p ->next;
}
if (c){
inode* nn = new inode();
nn->data = c;
current->next = nn;
current = nn;
}
return res_head;
}
寻找环的开始位置
循环链表:链表中一个结点的指针指向先前已经出现的结点,导致链表中出现环。
例子:
输入:A -> B -> C -> D -> E -> C [结点C在之前已经出现过]
//思路:使用一个map数组来记录已经遍历过的结点(地址),如果发现这个结点已经遍历过,则返回
inode* loop_start(inode* head){
inode* p = head->next;
map<inode*, bool> map_node;
while (p){
if (map_node[p])
return p;
map_node[p] = true;
p = p->next;
}
}
版权声明:本文为博主原创文章,转载请标明出处。