链表基本操作

package java程序员面试笔试宝典;


import java.io.ObjectInputStream.GetField;


class Node{
//链表节点定义
Node next;
int data;
public Node(int data){
this.data=data;
}
}


public class 题8_1链表基本操作 {
Node head=null;
public static void main(String[] args) {
题8_1链表基本操作 list=new 题8_1链表基本操作();
list.addNode(5);
list.addNode(3);
list.addNode(1);
list.addNode(2);
// list.addNode(8);
// list.addNode(7);
// list.deleteNode(0);
// list.printList();
System.out.println();
System.out.println("before order");
list.printList();
list.orderList0();
System.out.println();
System.out.println("after order");
list.printList();
//System.out.println(list.getNode(4).data);
}
//向链表中添加节点
public void addNode(int data){
Node newNode=new Node(data);
if(head==null){
head=newNode;
newNode.next=null;
return ;
}
if(head!=null){
Node p=head;
while(p.next!=null){
p=p.next;
}
p.next=newNode;
newNode.next=null;
}
}
//获得链表长度
public int length(){
int count=1;
Node p=head;
if(p==null){
return 0;
}
while(p.next!=null){
count++;
p=p.next;
}
return count;
}
//删除链表第i个节点,成功返回true,失败返回false
public boolean deleteNode(int i){
if(i<0||i>=length()||length()==0){
return false;
}
Node p=head;
if(i==0){
head=head.next;
return true;
}
if(i==1){
head.next=head.next.next;
return true;
}
int count=0;
Node pPre=null;
while(p.next!=null){
pPre=p;
p=p.next;
count++;
if(i!=length()-1&&count==i-1){
break;
}
}
if(p.next==null){
pPre.next=null;
return true;
}
if(p.next.next!=null){
p.next=p.next.next;
return true;
}else {
return false;
}

}
//获取链表最后指定索引的节点
public Node getNode(int index) throws NullPointerException{
if(head==null){
return null;
}
int count=0;
Node p=head;
while(count<index){
count++;
p=p.next;
}
if(p==null){
System.out.println("输入错误,索引值越界");
}
return p;
}
//打印链表
public void printList(){
Node p=head;
if(p==null){
return ;
}
//System.out.println("hahh");
System.out.print(p.data+"  ");
while(p.next!=null){
//System.out.println("你们");
p=p.next;
System.out.print(p.data+"  ");
}
}
//排序
public Node orderList0(){
if(head==null||head.next==null){
return head;
}
Node curNode=head;
Node nextNode=head.next;
while(curNode.next!=null){
while(nextNode!=null){
if(nextNode.data<curNode.data){
int temp=nextNode.data;
nextNode.data=curNode.data;
curNode.data=temp;
}
nextNode=nextNode.next;
}
curNode=curNode.next;
nextNode=curNode.next;
}
return head;
}
//对链表进行排序,返回排序后的头结点
public Node orderList(){
Node p=head;
if(p==null){
return null;
}
int temp=0;
int count=length();
while(count>=0){
p=head;
while(p.next!=null){
if(p.data>p.next.data){
temp=p.data;
p.data=p.next.data;
p.next.data=temp;
}
p=p.next;
}
count--;
}
return head.next;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值