题目:
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
@Override
public String toString() {
return val + "->" + next;
}
}
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
题解:
public class Solution {
//反转链表
public static ListNode reverseList(ListNode head) {
ListNode cur = head, pre = null;
while (cur != null) {
ListNode next = cur.next; // 暂存后继节点 cur.next
cur.next = pre; // 修改 next 引用指向
pre = cur; // pre 暂存 cur
cur = next; // cur 访问下一节点
}
return pre;
}
public static void main(String[] args) {
int[] arr = new int[]{2, 3, 4, 5};
ListNode head = new ListNode(1);
ListNode tail=head;
for (int i : arr) {
ListNode next = new ListNode(i);
tail.next = next;
tail=next;
}
System.out.println(head);
System.out.println(reverseList(head));
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之家整理,本文链接:https://www.bmabk.com/index.php/post/71510.html