今天部门测试,两道题:
1:删除一个单向链表中值为某个特定值的所有节点
2:把一个单向链表反转
第一个题目比较简单,第二个题目有点难,我吭哧半天没搞出来,丢人。。。
写在卷面上的答案要是搬到计算机上,100%得不到正确结果,呃,太依赖调试了。。。
Node类:
删除节点:
反转链表:
1:删除一个单向链表中值为某个特定值的所有节点
2:把一个单向链表反转
第一个题目比较简单,第二个题目有点难,我吭哧半天没搞出来,丢人。。。
写在卷面上的答案要是搬到计算机上,100%得不到正确结果,呃,太依赖调试了。。。
Node类:
/**
* chega
* 2012-12-5下午2:55:52
*/
/**
* @author chega
*
* 2012-12-5下午2:55:52
*
*/
public class Node
{
public int item;
public Node next;
public Node(int item){
this.item = item;
this.next = null;
}
public Node(int item, Node next){
this.item = item;
this.next = next;
}
public static Node createNodeList(int[] args){
Node nextNode = null;
Node node = null;
for(int i=args.length-1; i>=0;i--){
node = new Node(args[i], nextNode);
nextNode = node;
}
return node;
}
@Override
public String toString(){
if(this.next == null){
return this.item +"[next: null]";
}else{
return this.item +"[next: "+ this.next.item+"]";
}
}
public String getDetailDesc(){
StringBuilder sb = new StringBuilder();
sb.append(this.item);
Node head = this;
while(head.next != null){
sb.append("->" + head.next.item);
head = head.next;
}
return sb.toString();
}
}
删除节点:
/**
* @author chega
*
* 2012-12-5下午3:31:47
*
*/
public class DeleteNode
{
Node list = Node.createNodeList(new int[] { 1, 1, 3, 5, 7, 9, 1, 1 });
public static void main(String... args)
{
new DeleteNode().delete(1);
}
public void delete(int del)
{
System.out.println(list.getDetailDesc());
Node currNode = list;//从链表的head开始
Node previousNode = null;
while (currNode != null)
{
if (currNode.item == del)
{
if (previousNode != null)
{
//删除当前节点:把当前节点的next赋值给上一个节点的next即可
previousNode.next = currNode.next;
}
//如果previousNode == null说明删除的是链表的head,因此链表从head.next开始
else
{
list = list.next;
}
}
else
{
previousNode = currNode;
}
currNode = currNode.next;
}
System.out.println(list.getDetailDesc());
}
}
反转链表:
/**
* @author chega
*
* 2012-12-5下午2:57:40
*
*/
public class ReverseOneWayNodeList
{
Node list = Node.createNodeList(new int[]{1,3,5,7,9,1,2});
public static void main(String... args)
{
new ReverseOneWayNodeList().reverseNodeList();
}
public void reverseNodeList()
{
//前一个节点
Node previousNode = null;
//后一个节点
Node nextNode = null;
//当前节点
Node currNode = list;
while(currNode!= null){
nextNode = currNode.next;
currNode.next = previousNode;
previousNode = currNode;
currNode = nextNode;
}
//把上一个节点赋值给单向链表
list = previousNode;
System.out.println(list.getDetailDesc());
}
}