转载出处:https://blog.csdn.net/ctianju/article/details/116746451
题目
输入一个链表,反转链表后,输出新链表的表头。
思路
利用链表特性,依赖两个临时节点,进行链表的遍历赋值
java代码
public class ReverseList {
public static void main(String[] args) {
ListNode listNode = new ListNode(1);
ListNode listNode2 = new ListNode(2);
ListNode listNode3 = new ListNode(3);
ListNode listNode4 = new ListNode(4);
ListNode listNode5 = new ListNode(5);
listNode.next = listNode2;
listNode2.next = listNode3;
listNode3.next = listNode4;
listNode4.next = listNode5;
listNode5.next = null;
printListNode(listNode);
ListNode revserseNode = reverseList(listNode);
printListNode(revserseNode);
}
// 打印
public static void printListNode(ListNode listNode) {
ListNode tempNode = listNode;
while (tempNode != null) {
System.out.print(tempNode.val);
tempNode = tempNode.next;
}
System.out.println();
}
// nex保存下一节点,pre保存之前节点信息,,
public static ListNode reverseList(ListNode head){
ListNode next = null;
ListNode pre = null;
while (head !=null){
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}
class ListNode {
public int val;
ListNode next = null;
public ListNode(int val) {
this.val = val;
}
}