链表反转

来源:互联网 发布:微商加粉王软件下载 编辑:程序博客网 时间:2024/05/16 01:32
/*public class ListNode {    int val;    ListNode next = null;    ListNode(int val) {        this.val = val;    }}*/

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

循环实现,代码如下:

public class Circle_Reverse {    public ListNode ReverseList(ListNode head) {        if(null==head)            return head;        ListNode pre = head;        ListNode cur = head.next;        ListNode next;        while(null!=cur){            next = cur.next;            cur.next = pre;            pre = cur;            cur = next;        }        head.next=null;        head=pre;        return head;    }}

递归实现

public class Recursion_Reverse {    public ListNode ReverseList(ListNode head) {    if(null==head||null==head.next)            return head;        ListNode reverseHead = ReverseList(head.next);        head.next.next = head;//head.next的下一个节点为head(实现反转)        head.next = null;        return reverseHead;    }}
0 0
原创粉丝点击