链表反转系列

包括反转整个链表、从第k个节点开始反转链表
代码如下:

package lianbiaofanzhuang;
class Node
{
    int v;
    Node next;
    public Node(int v,Node next) {
        this.next=next;
        this.v=v;
    }
}
public class T1 {

    public static void main(String[] args) 
    {
        int[] data={1,4,5,6,8,0};
        Node next=null;
        for(int i=data.length-1;i>-1;i--)
        {
            Node node=new Node(data[i], next);
            next=node;
        }
        Node root=next;
        System.out.println("链表为");
        printList(root);
        Node reverseNode=reverse(root);
        System.out.println("整个列表反转");
        printList(reverseNode);
        System.out.println("从第三个节点开始反转");
        Node reverseNodeK=reverseNodeK(reverseNode, 3);
        printList(reverseNodeK);

    }
    //反转链表root
    static Node reverse(Node root)
    {
        Node cur=null;
        Node next=root;
        Node temp=root==null?null:root.next;
        while(next!=null)
        {
            next.next=cur;
            cur=next;
            next=temp;
            temp=temp==null?null:temp.next;
        }
        return cur;
    }
    //从链表的第k个节点饭庄链表(k>=2)
    static Node reverseNodeK(Node root,int k)
    {
        Node cur=root;
        Node pre=root;
        int i=1;
        while(cur!=null)
        {
            pre=cur;
            cur=cur.next;
            if(++i==k)
            {
                break;
            }
        }
        Node reverseNode=reverse(cur);
        pre.next=reverseNode;
        return root;
    }

    static void printList(Node root)
    {
        Node cur=root;
        while(cur!=null)
        {
            if(cur.next!=null)
            {
                System.out.print(cur.v+"->");
            }
            else 
            {
                System.out.println(cur.v);
            }
            cur=cur.next;
        }
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值