public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null)
return null;
ListNode pPre = null;
ListNode pNext = null;
while (head != null) {
pNext = head.next;
// 反转指向
head.next = pPre;
// 指针往下移动
pPre = head;
head = pNext;
}
// 新链表的头结点就是原链表的尾结点
return pPre;
}
void printList(ListNode last) {
while (last != null) {
System.out.print(last.val + ",");
last = last.next;
}
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(4);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(2);
Solution s = new Solution();
ListNode last = s.ReverseList(head);
s.printList(last);
}
}
java实现输入一个链表,反转链表后,输出链表的所有元素。
最新推荐文章于 2021-12-08 20:16:41 发布