Java数据结构与算法之-------如何把链表相邻的元素翻转

1.问题

     翻转链表相邻的元素,如给定链表1--2--3--4--5--6---7  。翻转后2--1--4--3--6--5--7

2 问题思路分析

  方法一:交换值法

      交换相邻两个元素的数据,不需要调整整个链表的结构,比较容易实现。

  方法二:就地逆序

    通过调整节点指针的指向来直接调换相邻的两个节点。

   1)如果单链表正好有偶数个节点,只需要将奇数偶数对调就行、

   2)如果链表有奇数个节点,那么只需要将最后一个节点去掉,其他的节点奇偶对调即可。

3代码实现

package linkedlist.Reverse;


import java.util.concurrent.Callable;

public class ReverseTest {
    public static void main(String[] args) {
        LNode head = ConstructList();
        System.out.println("没有进行翻转前:");
        print(head);
        System.out.println("翻转后:");
        Reverse(head);
        print(head);
    }

    //构造一个有环的链表,返回链表的头节点
    public static LNode ConstructList() {
        int i = 1;
        LNode head = new LNode();
        head.next = null;
        LNode tmp = null;
        LNode cur = head;
        for (; i < 8; i++) {
            tmp = new LNode();
            tmp.date = i;
            tmp.next = null;
            cur.next = tmp;
            cur = tmp;
        }
        return head;
    }



    /**
     *   翻转相邻的元素
     * @param head
     */
    public static void Reverse(LNode head){
        if (head==null||head.next==null){
            return;
        }
        LNode pre,cur,next;
        pre=head;
        cur=head.next;
        while (cur!=null&&cur.next!=null){//翻转  例如翻转链表 head--- 1--2---3---4---5---6---7
            next=cur.next.next;//(1)把cur的next.next暂存起来  比如  cur指向1  这时将3 暂存
            pre.next=cur.next;//(2)把头节点指向2
            cur.next.next=cur;//(3)  把2指向1
            cur.next=next;//(4) 1指向3
            pre=cur;//(5)后移 pre指向1
            cur=next;//(6)  后移  cur指向3
        }
    }

    public static void print(LNode head){
        for (LNode cur=head.next;cur!=null;cur=cur.next){
            System.out.print(cur.date+" ");
        }
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值