反转链表

解题思路

  根据链表的性质链表反转只能对每一个节点进行处理了,用三个节点标记当前节点、前节点、后节点,改变三者的链表关系,最后返回最后一个节点。注意在改变相互之间关系之前,要把后节点保存起来,也要注意循环的边界和返回的节点

问题描述

  输入一个链表,反转链表后,输出链表的所有元素

代码实现

 1 /*
 2 public class ListNode {
 3     int val;
 4     ListNode next = null;
 5 
 6     ListNode(int val) {
 7         this.val = val;
 8     }
 9 }*/
10 import java.util.Stack;
11 public class Solution {
12     public ListNode ReverseList(ListNode head) {
13         Stack<ListNode>    s = new Stack<ListNode>();
14         ListNode preNode     = null;
15         ListNode currentNode = head;
16         ListNode nextNode    = null;
17         while(currentNode != null){
18             nextNode = currentNode.next;
19             currentNode.next = preNode;
20             preNode = currentNode;
21             currentNode = nextNode;
22         }
23         return preNode;
24     }
25 }

 

posted @ 2018-03-07 11:06  休眠体  阅读(127)  评论(0编辑  收藏  举报