0.链表介绍
(1)
如图, 链表是一种非常常用的数据结构
链表头:指向第一个链表结点的指针
链表结点:链表中的每一个元素,包括:(1)当前结点的数据,(2)下一个结点的地址
链表尾:不再指向其他结点的结点,其地址部分放一个NULL,表示链表到此结束。
(2)
链表可以动态地创建
动态地申请内存空间:
int*pint = new int(1024); delete pint;
int*pint = new int[4]; delete[]pint;
动态地建立链表结点:
我们也可以把动态申请内存空间的两个操作符new和delete用来动态地申请和释放结构体类型的空间,就可以把它用到链表上了。下面的结构体只有两部分,一个是Int类型的id一个是指向student类型的指针。所以有了这个结构体我们就可以用这种方式来申请一片student类型的存储空间,比如如下面程序所示,先定义一个student类型的head,然后通过new student获得一片用来存放student类型变量的一片内存空间,并且把这片内存空间的地址赋给了head,通过这种方式我们就可以动态创建链表。
struct student
{
int id;
student* next;
};
student *head;
head = new student;
(3)逐步建立链表
(4)链表元素的遍历
#include<iostream>
using namespace std;
struct student
{
int id;
student* next;
};
student *create();
int main()
{
student* pointer = create();
while (pointer->next != NULL)
{
cout << pointer->id << endl;
pointer = pointer->next;
}
return 0;
}
(5)删除节点
1.假如被删除节点是第一个节点:
2.被删除节点是中间节点,需要用两个辅助指针,让被删除节点的前一个节点直接指向后一个节点
(6)插入结点。
1.在所有结点的前面插入结点
不能直接将head指向新的结点,若这样就相当于切掉了head与后面所有结点的联系。所以当我们想再链表中插入结点的时候,第一步一定是先让新插入的结点指向它的后续结点。从而保证后续的结点不会被丢失掉。
将结点unit插在最前面的情况:
unit->next = head;
head = unit;
2.在链表的中间插入结点
需要两个辅助指针,将结点Unit插入链表:
图中插入位置之前的结点由follow保存,插入位置之后的结点由temp保存。
2.两个单链表相交的起始节点(160)
编写一个程序,找到两个单链表相交的起始节点。
如下面的两个链表:
2.1 方法一 暴力搜索
对于A的每一个节点,看是否B中有与其相等的节点。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if (headA==NULL || headB==NULL)
return 0;
while(headA!=NULL)
{
ListNode *p=headB;
while(p!=NULL)
{
if(p==headA)
return p;
p=p->next;
}
headA=headA->next;
}
return NULL;
}
};
这种方法时间复杂度为O(N^2)。
2.2.方法二
首先遍历两个链表记录下它们的长度LenA和LenB,两者长度差为x。若存在交点, 则从最后一个结点到交点的位置两个链表的结点数一定是相同的,所以使较长的链表先向后移动x个位置(使长链表后面的长度与短链表相同),再开始对两个链表同时进行遍历(这是精髓),直到遍历到第一个相同结点时即为交点。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if (headA==NULL || headB==NULL)
return 0;
ListNode *p=headA;
ListNode *q=headB;
int lenA=0;
int lenB=0;
while(p!=NULL)
{
p=p->next;
lenA++;
}
while(q!=NULL)
{
q=q->next;
lenB++;
}
if (p!=q)
return NULL;
int dis = abs(lenA-lenB);
if(lenA>lenB)
{
for(int i=0;i<dis;i++)
headA=headA->next;
}
else
{
for(int i=0;i<dis;i++)
headB=headB->next;
}
while(headA!=headB)
{
headA=headA ->next;
headB=headB->next;
}
return headA;
}
};
最后执行结果:
这种方法因为最后headA和headB同时遍历,所以时间复杂度为O(N)。
3.其他链表相关
见博客:https://blog.csdn.net/xiangxianghehe/article/details/81739181