您的位置:首页 > 编程语言 > Java开发

Java实现--链表基本操作

2017-08-20 22:01 507 查看
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;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: