反转链表_JAVA

 1 package algorithms;
 2 
 3 /*
 4  * 
 5  * 
 6  *     输入一个链表,反转链表后,输出新链表的表头。
 7  * 
 8     public class ListNode {
 9         int val;
10         ListNode next = null;
11     
12         ListNode(int val) {
13             this.val = val;
14         }
15     }
16     
17     
18 */
19 
20 public class ReverseList {
21     public ListNode ReverseList_1(ListNode head) {
22         ListNode pReverseNodeHead = null;
23         ListNode pNode = head;
24         ListNode pPrevious = null;
25         while(pNode!=null) {
26             ListNode pNext = pNode.next;   //将下一个节点保存起来
27             if(pNext==null)
28                 pReverseNodeHead = pNode;
29             pNode.next = pPrevious;
30             pPrevious = pNode;
31             pNode = pNext;            //定义了几个指针 移动的时候要注意一起移动
32             
33         }
34         return pReverseNodeHead;
35 
36     }
37 }

 

posted @ 2019-03-27 20:54  Practical  阅读(165)  评论(0)    收藏  举报