題目描述
輸入一個(gè)鏈表抓于,反轉(zhuǎn)鏈表后,輸出鏈表的所有元素蚤假。
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode pre = head;
ListNode in = null;
ListNode post = null;
if(pre == null)
return null;
if(pre.next == null)
return pre;
in = pre.next;
pre.next = null;
post = in.next;
while(post != null) {
in.next = pre;
pre = in;
in = post;
post = in.next;
}
in.next = pre;
return in;
}
public static void main(String[] args) {
ListNode head = new ListNode(0);
ListNode node = head;
for(int i = 1; i <= 10; i++) {
ListNode temp = new ListNode(i);
node.next = temp;
node = node.next;
}
node = head;
while(node != null) {
System.out.println(node.val);
node = node.next;
}
Solution obj = new Solution();
node = obj.ReverseList(head);
while(node != null) {
System.out.println(node.val);
node = node.next;
}
}
}