Subject description:
After entering a list inverted list, the new list of the output header.
Thinking: with two pointers, one pointer is used to save the next node after head.next,
Then prev pointer to the previous node of the current node, the current node is a next node point to the front.
Finally, after the current node and the current node before a shift is performed
Code:
package offer;
public class TestNo15 {
static class ListNode{
int val;
ListNode next;
ListNode(int x){
val = x;
}
public String toString(){
if(this.next==null){
return String.valueOf(this.val);
}else{
return this.val +"->" + this.next.toString();
}
}
}
public static void main(String[] args) {
ListNode head = new ListNode(0);
ListNode newHead = head;
for(int i= 1;i<5;i++){
newHead.next = new ListNode(i);
newHead = newHead.next;
}
System.out.println(new TestNo15().ReverseList(head));
}
//非递归反转链表
public ListNode ReverseList(ListNode head) {
ListNode prev = null;
ListNode next = null;
while (head != null) {
next = head.next; // next保存head的下一个节点
head.next = prev; // 将当前节点的next断开,指向前一个节点,实现反转
prev = head;//将当前节点的前节点进行后移
head = next;//将当前节点进行后移
}
return prev;
}
}