Java实现--链表基本操作

package lintcode;


import java.util.Hashtable;
class Node{
Node next=null;
int data;
public Node(int data){
this.data=data;
}
}
/** 
* @ClassName: MyLinkedList 
* @Description: TODO() 
* @author LLL 
* @date 2017年8月20日 下午9:30:27 
*  
*/
public class MyLinkedList {
   Node head=null;
    /**
     * 
    * @Title: addNode 
    * @Description: TODO(向链表中插入数据) 
    * @param @param d    设定文件 
    * @return void    返回类型 
    * @throws
     */
public void addNode(int d){
Node newNode=new Node(d);
if(head==null){
head=newNode;
return;
}
Node tmp=head;
while(tmp.next!=null){
tmp=tmp.next;
}
tmp.next=newNode;
}
/**

* @Title: deleteNode 
* @Description: TODO(删除第inde结点) 
* @param @param index
* @param @return    设定文件 
* @return Boolean    返回类型 
* @throws
*/
public Boolean deleteNode(int index){
if(index<1 || index>length()){
return false;
}
if(index==1){
head=head.next;
return true;
}
int i=1;
Node preNode=head;
Node curNode=preNode.next;
while(curNode!=null){
if(i==index){
preNode.next=curNode.next;
return true;
}
preNode=curNode;
curNode=curNode.next;
i++;
}
return true;
}
/** 
* @Description: TODO() 
* @param  @return   
* @return int   
* @throws 
*/
public int length() {
// TODO Auto-generated method stub
int length=0;
Node tmp=head;
if(tmp!=null){
length++;
tmp=tmp.next;
}
 return length;
}
/** 
* @Description: TODO(删除链表中重复) 
* @param  @param head   
* @return void   
* @throws 
*/
public void deleteDuplecate(Node head){
Hashtable<Integer, Integer> table=new Hashtable<Integer,Integer>();
Node tmp=head;
Node pre=null;
while(tmp!=null){
if(table.containsKey(tmp.data))
pre.next=tmp.next;
else{
table.put(tmp.data, 1);
pre=tmp;
}
tmp=tmp.next;
}
}
/**

* @Description: TODO(找出单链表中的倒数第k个元素) 
* @param  @param head
* @param  @param k
* @param  @return   
* @return Node   
* @throws
*/
public Node findElem(Node head,int k){
if(k<1 || k>this.length())
return null;
Node p1=head;
Node p2=head;
for(int i=0;i<k-1;i++)//前移k-1步
p1=p1.next;
while(p1!=null){
p1=p1.next;
p2=p2.next;
}
return p2;
}
/**

* @Description: TODO(链表反转) 
* @param  @param head   
* @return void   
* @throws
*/
public void ReverseIteratively(Node head){
Node pReversedHead=head;
Node pNode=head;
Node pPrev=null;
while(pNode!=null){
Node pNext=pNode.next;
if(pNext==null)
pReversedHead=pNode;
pNode.next=pPrev;
pPrev=pNode;
pNode=pNext;
}
this.head=pReversedHead;
}





}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值