单向链表的删除和反转

今天部门测试,两道题:
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());
}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值