翻转链表

来源:互联网 发布:banner设计软件 编辑:程序博客网 时间:2024/05/14 14:08

问题描述:

翻转一个链表

样例

给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null

解1:

/** * 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 node=new ListNode(0);                 while(head!=null)        {            ListNode tmp=head.next;            ListNode next=node.next;            node.next=head;            node.next.next=next;            head=tmp;        }                return node.next;    }}

解2:

/** * 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 node=new ListNode(head.val);          head=head.next;        while(head!=null)        {            ListNode tmp=head.next;            head.next=node;            node=head;            head=tmp;        }                return node;    }}


原创粉丝点击