中级农民
- 积分
- 105
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2017-9-24
- 最后登录
- 1970-1-1
|
- class Node {
- char c;
- Node next;
- Node (char c_){
- c = c_;
- }
- }
- public class reverseLinkedListWords {
- public static Node reverseWords(Node head){
- if(head == null || head.c == ' ') return head;
- Node start = head;
- Node pause = head;
- while(pause != null && pause.c != ' '){
- pause = pause.next;
- }
- Node new_head = reverse(start, pause);
- if(pause!= null) pause.next = reverseWords(pause.next);
- return new_head;
- }
- private static Node reverse(Node start, Node tail){
- Node cur = start;
- Node prev = tail;
- while(cur != tail){
- Node next = cur.next;
- cur.next = prev;
- prev = cur;
- cur = next;
- }
- return prev;
- }
- public static void main(String[] args) {
- String s = "I am a good student";
- Node dummy = new Node(' ');
- Node p = dummy;
- for(char c: s.toCharArray()){
- p.next = new Node(c);
- p = p.next;
- }
- Node new_head = reverseWords(dummy.next);
- p = new_head;
- while(p != null){
- System.out.print(p.c); // "I ma a doog tneduts"
- p = p.next;
- }
- }
- }
复制代码
|
|