链表操作汇总

创建新的节点

返回链表头指针并且将节点初始化。

struct node{
	int val;
	node *next;
};
node * creatNode(){
	node *newNode=new node;
	newNode->next=NULL;
	newNode->val=0;
	return newNode;
}

创建链表

输入n个值,创建一个长度为n的链表

node *creatList(int n){
	node *head=creatNode();
	node *last=head;
	for( int i=1;i<=n;i++){
		node *temp=creatNode();
		cin>>temp->val;
		last->next=temp;
		last=temp;
	}
	return head;
}
node *creatList(int n,int *a){
	//将数组a中的元素创建成链表 
	//数组a必须从1开始 
	node *head=creatNode();
	node *last=head;
	for( int i=1;i<=n;i++){
		node *temp=creatNode();
		temp->val=a[i];
		last->next=temp;
		last=temp;
	}
	return head;
}

输出链表

void  printList(node *head){
	for( node *i=head->next;i!=NULL;i=i->next){
		cout<<i->val<<" ";
	}
	return ;
}

void PrintList(Node h){
    if(h.ne==NULL){
        cout<<"NULL"<<endl;
        return ;
    }
    for( Node *i=h.ne;i!=NULL;i=i->ne){
        cout<<i->val<<" ";
    }
    cout<<endl;
}

在链表中查找某个值的个数

在以head为头的链表中寻找val数值,返回val的个数

int countNumber( node *head,int val){
	int res=0;
	for( node *i=head->next;i!=NULL;i=i->next){
		if(i->val==val) res++;
	}
	return res;
}

在链表中查找某个值的位置

int findNumber( node*head,int val){
	int res=0;
	for( node *i=head->next;i!=NULL;i=i->next){
		res++;
		if(i->val==val) return res;
	}
	return -1;
}

删除链表中第pos个元素

bool eraseNode(node *head,int pos){
	int cnt=1;
	for( node *i=head;i!=NULL;i=i->next){
		if(pos==cnt++){
			node *temp=i->next;
			i->next=i->next->next;
			delete temp;
			return 1;
		}
	}
	return 0;
}

在链表尾添加结点

void AddNode( Node &h,int val){
    Node *last=&h;
    while(last->ne!=NULL) last=last->ne;
    List *New=new List;
    last->ne=New;
    New->ne=NULL;
    New->val=val;
    return ;
}

找到倒数第i个结点

Node * FindMthNode( Node h,int pos){
    int len=0;
    for( Node *i=&h;i->ne!=NULL;i=i->ne){
        len++;
    }
    len=len-pos+1;
    for( l *i=&h;i->ne!=NULL;i=i->ne){
        if(--len==0){
            return i->ne;
        }
    }
}

链表反转

void  ReverseList( Node &h){
    Node *nowNode;
    for( Node * i=h.ne;i->ne!=NULL;){
        nowNode=i->ne;
        i->ne=i->ne->ne;
        nowNode->ne=h.ne;
        h.ne=nowNode;
    }
    return ;
}

链表合并

Node MergeList(Node a,Node b){
    Node h;
    h.ne=NULL;
    Node *res=&h;
    Node *i=a.ne,*j=b.ne;
    while(i!=NULL||j!=NULL){
        int val;
        if(i==NULL) val=j->val,j=j->ne;
        else if(j==NULL) val=i->val,i=i->ne;
        else {
            if(i->val>j->val)  val=j->val,j=j->ne;
            else val=i->val,i=i->ne;
        }
        Node * newNode = new Node;
        newNode->ne=NULL;
        newNode->val=val;
        res->ne=newNode;
        res=res->ne;
    }
    return h;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值