验证中...
ReverseList_15.java
Raw Copy
/**
*
* @author ChopinXBP
* 输入一个链表,反转链表后,输出新链表的表头。
*
*
*/
public class ReverseList_15 {
public static class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ListNode head = new ListNode(0);
ListNode p = head;
for (int i = 0; i < 5; i++) {
ListNode newnode = new ListNode(i + 1);
p.next = newnode;
p = p.next;
}
p = head;
System.out.print("原序列: ");
for (int i = 0; i < 6; i++) {
System.out.print(p.val);
p = p.next;
}
p = Solution(head);
System.out.print("\n翻转序列: ");
for (int i = 0; i < 6; i++) {
System.out.print(p.val);
p = p.next;
}
}
public static ListNode Solution(ListNode head) {
if (head == null)
return null;
else if (head.next == null)
return head;
ListNode temp = head.next; //指向前一个结点
ListNode later = head; //指向后一个结点
//每次循环先定义一个former指向下一个结点,将temp与later所指结点反向,并依次前进later与temp
while (temp.next != null) {
ListNode former = temp.next; //指向下一个结点
temp.next = later;
later = temp;
temp = former;
}
temp.next = later; //将最后两个结点反向
head.next = null; //去掉头两个结点的自循环
return temp;
}
}

Comment list( 0 )

You need to Sign in for post a comment

Help Search