题目描述
输入一个链表,反转链表后,输出新链表的表头。
分析
当前节点是head,pre为当前节点的前一节点,next为当前节点的下一节点.
需要pre和next的目的是让当前节点从pre->head->next1->next2变成pre<-head next1->next2即pre让节点可以反转所指方向,但反转之后如果不用next节点保存next1节点的话,此单链表就此断开了所以需要用到pre和next两个节点.
具体操作:
next = head.next; //先保存当前节点的下一个节点
head.next = pre; // 当前节点指向pre
pre = head; //当前节点赋值给pre,即当前节点前移一位
head = next; //原当前节点的下一个节点赋值给当前节点,即下一节点前移一位
源代码
public class Dome5_plus {
int data;
Dome5_plus next=null;
Dome5_plus(int data){
this.data=data;
}
public static void main(String[] args) {
Dome5_plus head=new Dome5_plus(0);
Dome5_plus head1=new Dome5_plus(1);
Dome5_plus head2=new Dome5_plus(2);
Dome5_plus head3=new Dome5_plus(3);
head.data=0;
head.next=head1;
head1.next=head2;
head2.next=head3;
System.out.println(head.data+"->"+head1.data+"->"+head2.data+"->"+head3.data);
head=head.ReverseList(head);
System.out.println(head.data+"->"+head1.data+"->"+head2.data+"->"+head3.data);
}
/**
*
* @param head 目标头节点
* @return 翻转后的头结点
*/
public Dome5_plus ReverseList(Dome5_plus head) {
Dome5_plus pre = null;
Dome5_plus next = null;
if (head == null) {//如果节点为空的话,就返回null
return null;
}
while (head != null) {
//先保存当前节点的下一个节点
next = head.next;
//当前节点指向pre
head.next = pre;
//当前节点赋值给pre,即当前节点前移一位
pre = head;
//原当前节点的下一个节点赋值给当前节点,即下一节点前移一位
head = next;
}
return pre;
}
}