单链表的常用操作

版权声明:本文为博主原创文章,转载请注明出处 https://blog.csdn.net/jingshuiliushen_zj/article/details/83548376

生活果然是需要一点刺激的,从今天开始,我一定要好好写博客!!
首先链表的节点定义:

class Node{
	public int data;
	public Node next;
}

以下操作假设单链表有头结点(head!=null)。

1、末尾添加节点

public void addNode(Node node){
	Node current=head;//head是单链表的头结点
	while(current.next!=null){
		current=current.next;
	}
	current.next=node;
}

2、指定位置插入节点

public void insert(Node node,int idx){
	Node current =head;
	if(idx<1||idx>length()+1){
		print("插入位置不合法")
	}
	int temp=1;
	while(current.next!=null){
		if(temp<idx){//遍历单链表,找到插入位置
			current=current.next;
			temp++;
		}else{
			node.next=current.next;
			current.next=node;
			return ;
		}
	}
}

3、删除指定位置的节点

public void delete(int idx){
	Node current =head;
	if(idx<1||idx>length()+1){
		print("删除位置不合法")
	}
	int temp=1;
	while(current.next!=null){
		if(temp<idx){//遍历单链表,找到删除位置
			current=current.next;
			temp++;
		}else{
			current.next=current.next.next;
			return ;
		}
	}
}

4.1、单链表逆置(递归),举个例子,逆置a->b->c->d

public void reverse(Node current,Node head){//head保存逆置后的头结点
	if(current.next==null){
		head=current;
	}else{
		Node pNext=current.next;
		reverse(pNext,head);//逆置b->c->d
		pNext.next=current;
		current.next=null;
	}
}

4.2、单链表逆置(非递归)

public Node reverse(Node head){
	Node p=head.next;
	head.next=null;
	Node q;//q指向下一节点,保证链表的不断裂,,head永远指向头结点
	while(p){
		q=p.next;
		p.next=head.next;
		head.next=p;
		p=q;
	}
}

猜你喜欢

转载自blog.csdn.net/jingshuiliushen_zj/article/details/83548376
今日推荐