反转单向链表

思路一:定义三个节点分别为当前节点cur,前一个节点pre,后一个节点next
我们需要当前节点由指向next转变为指向pre,并且我们必须先将下一个节点缓存起来否则改变了当前节点的指向
我们无法继续遍历整个链表了。
即步骤如下
1 缓存当前节点的下一个节点 next=cur.next;
2 将当前节点指向前一个节点 cur.next=pre;
3 前一个节点后移一位,指向当前节点;pre=cur;
4 当前节点后移一位 cur=next;
 
  public ListNode ReverseList(ListNode head) {

    ListNode cur = head;

    ListNode pre = null;

    ListNode next = null;

    while (cur != null) {

        next = cur.next;

        cur.next = pre;

        pre = cur;

        cur = next;

    }

    return pre;

    }

 

思路二:借助于栈结构,首先遍历链表并且存储于栈中,接着 根据弹栈的顺序重新遍历栈并且更改每个
节点的值  当然,在这里是通过改变每个节点的值来达到效果的 并没有 改变节点的 引用关系
 
 public ListNode ReverseList(ListNode head) {

    ListNode cur = head;

            ListNode pre = head;

            ListNode next = null;

           //借助栈的数据结构

            Stack stack = new Stack();

            while(cur!=null){

                stack.push(cur.val);

                cur=cur.next;

            }

            while(!stack.isEmpty()){

                pre.val=(int) stack.pop();

                pre=pre.next;

            }

            return head;

    }

 

思路三 采用递归实现
public ListNode ReverseList(ListNode head) {

        if (null == head || null == head.next) {  

          return head;  

             }  

        ListNode reversedHead = ReverseList(head.next);  

        head.next.next=head;  

        head.next=null; 

        return reversedHead; 

            }

 

posted @ 2016-04-03 01:14  winAlaugh  阅读(237)  评论(0编辑  收藏  举报