lintCode:反转链表

来源:互联网 发布:jira mysql配置 编辑:程序博客网 时间:2024/05/13 08:27
/** * Definition for ListNode. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int val) { *         this.val = val; *         this.next = null; *     } * } *///该方法存取了三个节点,防止链表中断public class Solution {    /*     * @param head: n     * @return: The new head of reversed linked list.     */    public ListNode reverse(ListNode head) {        // write your code here        if(head==null){            return null;        }        ListNode temp = head;         ListNode temp1 = null;        ListNode temp2 = null;        if(head.next!=null){            temp1 = head.next;        if(head.next.next!=null){            temp2 = head.next.next;        }        }        head.next = null;        while(temp2!=null){           temp1.next = head;           head = temp1;           temp1 = temp2;           temp2 = temp2.next;        }           if(temp2 == null){              if(temp1!=null){              temp1.next = head;              head = temp1;              }           }               return head;                  }}

还有一种方法更为简单。就是将链表每一个元素存入栈中,然后进行操作,但是会浪费空间,lintcode不让通过
原创粉丝点击