题目
输入一个链表,反转链表后,输出新链表的表头。
思路
将原来的链表作为链表A,定义一个current节点,赋值为链表A的head,新建一个空节点newCode,定义一个n节点,赋值为head.next。
操作: current指向空节点newCode,然后将空节点newCode的值赋值为current。接着current赋值为n。如果n不是null的话,才进行赋值。
因为如果是null的话,下一循环时,current就没必要指向newCode了。
流程图:
代码
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public ListNode reverseListNode(ListNode head){
if(head==null) return null;
ListNode current=head;
ListNode n=head.next;
ListNode newNode=null;
while(current!=null){
current.next=newCode;
newCode=current;
current=n;
if(n!=null){
n=n.next;
}
}
return newNode;
}