0
点赞
收藏
分享

微信扫一扫

链表常用方法

千妈小语 2022-03-21 阅读 38
链表

头插法:

struct LinkList List_HeadInsert(struct LinkList &L){
LNode *s;
int x;
L=(struct ListNode)malloc(sizeof(struct ListNode));
L->next=NULL;
while(x!=999){
s=(struct ListNode*)malloc(sizeof(struct ListNode));
s->data=x;
s->next=L->next;
L->next=s;
scanf("%d",&x);
}
return L;
}

尾插法:

struct ListNode List_TailInsert(struct ListNode &L){
int x;
L=(struct ListNode)malloc(struct ListNode);
LNode *s,*r=L;
while(x!=999){
s=(struct ListNode)malloc(struct ListNode);
s->data=x;
r->next=s;
r=s;
scanf("%d",&x);
}
return L;
}

逆置法:

struct ListNode * reverseList(struct ListNode &L){
if(head==NULL||head->next==NULL)
return head;
struct ListNode *prev=NULL;
struct ListNode *cur=head;
while(cur){
struct ListNode *curp=cur->next;
cur->next=prev;
prev=cur;
cur=curp;
}
return prev;
{

归并法:

​
struct node *sumw(struct node *x1,struct node *x2 )
{undefined
    struct node *p,*q;
    struct node *tail;
    p=x1->next;
    q=x2->next;
    tail=x1;
    free(x2);//将链表2的头链表释放
    while (p&&q) {undefined
        if (p->data < q->data) {
            tail->next=p;
            tail=p;
            p=p->next;
        }else
        {
            tail->next=q;
            tail=q;
            q=q->next;
        }
    }
    if (p)
        tail->next=p;
    else
    
        tail->next=q;
    
    
    return x1;
}

​

双指针:

struct ListNode* middleNode(struct ListNode* head){    
	struct ListNode* fast, *slow;    
	fast = slow =head;    
	while(fast && fast->next){        
		slow = slow->next;        
		fast = fast->next->next;    
	}    
return slow;
}
举报

相关推荐

0 条评论