1. 递归删除指定值(无头结点)
void Del(ListNode* L,int val){
ListNode* p;//指向被删除节点
if(L==NULL) return;//递归边界
if(L->val==val){//处理首指针
p = L;
L = L->next;
free(p);//删除节点
Del(L,val);//递归调用
}
else Del(L->next,val);//递归调用
}
2. 循环删除指定值(有头结点)
void Del(ListNode* L,int val){
ListNode* p = L->next;//遍历节点
ListNode* pre = L;//辅助删除节点
ListNode* q;//删除节点
while(p!=NULL){//遍历节点存在
if(p->val==val){//找到指定值,更改指针结构
q = p;
p = p->next;
pre->next = p;
free(q);
}
else{
pre = p;
p = p->next;
}
}
}
3. 反向输出每个值(有头结点)
//主函数从头结点下一个节点调用函数
void rprint(ListNode* L){
if(L->next) rprint(L->next);//入栈
print(L->val);
}
4. 删除最小值(有头结点)
void del_min(ListNode* L){
ListNode* pre = L; ListNode* p = pre->next;
ListNode* minpre = pre; ListNode* minp = p;
while(p){
if(p->val<minp->val){
minp = p;
minpre = pre;
}
pre = p;
p = p->next;
}
minpre->next = minp->next;
free(minp);
}
5. 就地逆置(有头结点)
ListNode* reverseList(ListNode* head) {
ListNode*pre= head;
head = head->next;
ListNode*node;//插入节点
while(head){
node = head;
head = head->next;
node->next = pre->next;
pre->next = node;
}
return pre;
6. 递增有序(有头结点)
void sort(ListNode* head){
ListNode* p = head->next;//遍历节点
head->next = NULL;//断链
ListNode* node;//插入节点
while(p){
node = p;
p = p->next;
insert(head,node);//插入重构链表
}
}
void insert(ListNode* pre,ListNode* node){//将node插入到头结点为pre的链表中
while(pre->next&&pre->next->val<node->val)
pre = pre->next;//找到插入位置的前驱
node->next = pre->next;
pre->next = node;
}
7. 删除指定范围值(与题2基本一致)
8. 求两链表公共节点(相交链表)
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if (headA == NULL || headB == NULL)
return NULL;
ListNode *pA = headA, *pB = headB;
while (pA != pB) {
pA = pA == NULL ? headB : pA->next;
pB = pB == NULL ? headA : pB->next;
}
return pA;
}
9. 递增输出并释放(循环调用题4函数)
10. 按奇偶拆分
ListNode * split(ListNode *A){
int i =0;//判断序号
ListNode * B = new ListNode();
ListNode * ra = A, rb = B;//链表遍历指针
ListNode *p = A->next;//拆分A的遍历指针
while(p){//每次处理一个元素
i++;
if(i%2==0) rb->next=p,rb=p;//更改下条件可以用来处理奇数偶数
else ra->next=p,ra=p;
p = p->next;
}
ra->next = NULL;
rb->next = NULL;
return B;
}
标签:pre,node,head,ListNode,应用题,next,链表,NULL
From: https://www.cnblogs.com/929code/p/16608493.html