package demo;
/*
* 题目描述
输入一个链表,反转链表后,输出链表的所有元素。
*/
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Offer_36 {
public ListNode ReverseList(ListNode head) {
ListNode result = null;// 保存结果的ListNode
ListNode pNode = head;// 暂存结点
if (head == null)// 若头结点为空,则返回null
return null;
ListNode pPrev = null;
while (pNode != null) {// 结点不为空,则交换结点位置
ListNode pNext = pNode.next;
if (pNext == null)
result = pNode;
pNode.next = pPrev;
pPrev = pNode;
pNode = pNext;
}
return result;
}
public static void main(String[] args) {
Offer_36 off = new Offer_36();
ListNode head = new ListNode(1);
ListNode head1 = new ListNode(2);
ListNode head2 = new ListNode(3);
ListNode head3 = new ListNode(4);
ListNode head4 = new ListNode(5);
head.next = head1;
head1.next = head2;
head2.next = head3;
head3.next = head4;
head4.next = null;
System.out.println(off.ReverseList(head).next.next.val);
}
}
反转链表
最新推荐文章于 2024-03-04 13:53:41 发布