您的位置:首页 > 其它

反转链表

2017-03-18 14:34 120 查看
题目: 反转链表

代码如下:

package problem2;
/**
* @author Hutongling
*/
public class 反转链表 {
static void reverseList(Node head){
if(head==null)
return ;
Node head1=new Node(head.value);//此处一定需要注意,一定要新建一个值为head.value的节点,因为头结点的next不为空,如果直接将头节点赋给该新建的节点的话,其next就不为空了。
Node temp;
while(head.next!=null){
temp=head.next;
head.next=head1;
head1=head;
head=temp;
}
head.next=head1;
while(head.next!=null){
System.out.print(head.value + " ");
head=head.next;
}
}

public static void main(String[] args) {
int data[]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,20,30};
Node head1=new Node(data[0]);   //新建链表的头结点
Node head2=head1;               //保留链表的头结点

for(int i=1;i<data.length;i++){ //用尾插法创建一个链表
Node node1=new Node(data[i]);
head1.next=node1;
head1=node1;
}
reverseList(head2);
}

}


结果如下:

30 20 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  链表