链表头结点: 设置头结点是为了保证处理第一个节点和后面的节点的时候设计的算法相同,实现程序的高效性。
1 初始化链表
bool InitList(LinkList *L)
{
(*L)=(LinkList)malloc(sizeof(Node));
if(!(*L))
return false;
(*L)->next=NULL;
return true;
}
2 在链表(*L)的第i个node位置,插入元素e
bool ListInsert(LinkList *L,int i,ElemType e)
{
LinkList p;
p=*L;
int j;
j=1;
while(p && j<i)
{
p=p->next;
++j;
}
if(!p || j>i)
return false;
LinkList s;
s=(LinkList)malloc(sizeof(Node));
s->data=e;
s->next=p->next;
p->next=s;
return true;
}
3 建立带表头节点的 单链线性表L (尾插法)
void CreateListTail(LinkList *L,int &cnt)
{
*L=(LinkList)malloc(sizeof(Node));
LinkList p,r;
r=*L;
ElemType e;
while(cnt--)
{
scanf("%d",&e);
p=(Node *)malloc(sizeof(Node));
p->data=e;
r->next=p;
r=p;
}
r->next=NULL;
}
4 链表的new 创建法
struct ListNode
{
int val;
ListNode *next;
};
void Create(ListNode** L,int len)
{
ListNode* p;
*L=new ListNode;
}
5 链表排序()
5.1 快速排序

代码
Node* partion(Node* pBegin, Node* pEnd)
{
if(pBegin == pEnd || pBegin->next == pEnd)
return pBegin;
ElemType key=pBegin->data;
Node *p=pBegin;
Node *q=pBegin;
while(q != pEnd)
{
if(q->data<key)
{
p=p->next;
swap(p->data,q->data);
}
q=q->next;
}
swap(p->data,pBegin->data);
return p;
}
void quick_sort(Node *pBegin, Node *pEnd)
{
if(pBegin == pEnd || pBegin->next == pEnd)
{
return;
}
Node *mid=partion(pBegin, pEnd);
quick_sort(pBegin, mid);
quick_sort(mid->next,pEnd);
}
Node *sortList(Node *head)
{
if(head == NULL || head->next == NULL)
return head;
quick_sort(head,NULL);
return head;
}
5.2
5.3
6 求链表的交集与并集
6.1并集(求并集,并且删除重复元素)(开了一个vector,用来存放俩个链表相同元素)
void inter_sec(LinkList *A,LinkList *B)
{
LinkList a_tmp=*A;
LinkList b_tmp=*B;
a_tmp=a_tmp->next;
vector<int> arr;
while(a_tmp)
{
while(b_tmp->next)
{
if(b_tmp->next->val==a_tmp->val)
{
arr.push_back(a_tmp->val);
LinkList p=b_tmp->next;
b_tmp->next=p->next;
free(p);
break;
}
b_tmp=b_tmp->next;
}
a_tmp=a_tmp->next;
}
sort(arr.begin(),arr.end());
cout<<"A cross B is ";
for(int i=0;i<=arr.size()-1;i++)
cout<<arr[i]<<" ";
cout<<endl;
}
7 链表逆序输出和删除duplicate(共同点: 三个辅助node)
链表反转
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode pre = head;
ListNode cur = head.next;
ListNode nex = null;
while(cur != null)
{
nex = cur.next;
cur.next = pre;
pre = cur;
cur = nex;
}
head.next = null;
return pre;
}
}
删除 duplicate, 并且重复节点不保留, 一起删掉
参考文献

无序链表的重复项删除(利用HashSet)
HashSet方法参考文献
public class Solution {
public ListNode removeDuplicates(ListNode head) {
Set<Integer> set = new HashSet<>();
ListNode node = new ListNode(0);
ListNode newHead = node;
while(head != null){
if(!set.contains(head.val)){
set.add(head.val);
node.next = head;
node = node.next;
}
head = head.next;
}
node.next = null;
return newHead.next;
}
}
8