标签:temp SingListNode 单向 next 链表 数组 root public
public class SingListNode {
//链表类
int val;
SingListNode next;
public SingListNode(int val) {
this.val = val;
}
}
public class SingListNodeInser {
SingListNode root ;
/*
将数组转化为链表
*/
public SingListNode arrayToListNode(int[] arr){
//生成链表的根节点,并将数组的第一个元素的值赋给链表的根节点
SingListNode root = new SingListNode(arr[0]);
SingListNode other = root; //other作为临时变量
for (int i = 1;i<arr.length;i++){ //从1开始遍历数组
SingListNode temp = new SingListNode(arr[i]);//每循环一次生成一个新的节点
other.next = temp; //将other的下一个节点指向生成的新节点
other = temp; //other为临时变量,指向当前节点
// if(i==arr.length-1){
// temp.next = null;
// }
}
this.root = root;
return root;
}
/*
将元素插入链表
*/
public void addnode(SingListNode node){
SingListNode temp = root; //临时变量
if (root.next == null){
root.next = node;
System.out.println("到尾了");
return;
}
while (temp.next!=null&&temp.next.val<node.val){
temp = temp.next; //往下遍历下一个节点
}
if (temp.next == null){//到链表尾
temp.next = node;
node.next = null;
}else {
node.next = temp.next;
temp.next = node;
}
System.out.println("节点"+node.val+"插入成功");
}
/*
遍历链表
*/
public void printListNode(){
SingListNode temp = root;
while (temp!=null){
System.out.print(temp.val+" ");
temp = temp.next;
}
}
}
public class test09 {
public static void main(String[] args) {
int[] arr = {1,3,5,6,7,8};
SingListNodeInser singListNodeInser = new SingListNodeInser();
SingListNode listNode = singListNodeInser.arrayToListNode(arr);
singListNodeInser.addnode(new SingListNode(8));
singListNodeInser.addnode(new SingListNode(2));
singListNodeInser.addnode(new SingListNode(77));
singListNodeInser.printListNode();
}
}
结果:
标签:temp,SingListNode,单向,next,链表,数组,root,public 来源: https://blog.csdn.net/Gsasuke/article/details/113796093
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。